CSS Units

Explore the different types of units in CSS and learn how to use them effectively to build robust and responsive layouts.

Absolute vs. Relative Units

CSS units are used to specify lengths, sizes, and other dimensions for elements. They can be broadly categorized into two types: **absolute** and **relative**.

**Absolute units** are fixed and do not change based on other elements. They are useful for print media but are generally not recommended for screen design as they do not adapt to different screen sizes.

**Relative units** are dynamic and scale relative to something else, such as the parent element's font size, the root element's font size, or the viewport dimensions. These are the preferred units for building responsive websites.

Common Absolute Units

px (Pixels)

A fixed number of pixels. The most common absolute unit, but not ideal for responsiveness.

pt (Points)

A point is $1/72$ of an inch. Often used in print media, but rarely in web development.

cm, mm, in

Centimeters, millimeters, and inches. Primarily used for print layouts, not screen.

Common Relative Units

em

Relative to the font size of the **parent** element. Can cause cascading sizing issues.

rem

Relative to the font size of the **root** (html) element. Highly recommended for consistent typography.

% (Percentage)

Relative to the size of the parent element. Often used for fluid layouts and widths.

vw, vh

Viewport width and viewport height. Relative to the browser window's size. Ideal for full-screen elements.

Live Example: em vs. rem

This example demonstrates the key difference between em and rem. The em unit is based on its parent's font size, which can lead to a compounding effect. The rem unit, however, is always based on the root font size, providing more predictable and consistent scaling.

Parent with font-size: 1.5em

Child with font-size: 1.5em (relative to its parent)

Parent with font-size: 1.5rem

Child with font-size: 1.5rem (relative to the root)