CSS Units

Units are everywhere in CSS. You’ll use them daily to set lengths, paddings, margins, font sizes, widths, heights, and alignment.

Common units include px, em, rem, and %, but CSS also supports more specialized ones. Let’s break them down.

Pixels (px)

The most widely used unit.

  • A CSS pixel doesn’t map directly to a physical screen pixel (since devices vary in DPI and resolution).
  • Browsers use conventions to make px consistent across devices.

Example:

Code Block Loading...

Percentages (%)

Percentages are relative to the parent element’s property.

Example:

Code Block Loading...

Real‑world Measurement Units

These map to physical dimensions. They’re rarely used on screens but can be useful for print stylesheets:

  • cm → centimeters (1cm ≈ 37.8px)
  • mm → millimeters (0.1cm)
  • q → quarter millimeter
  • in → inches (1in = 96px)
  • pt → points (1in = 72pt)
  • pc → picas (1pc = 12pt)

Relative Units

Relative units adapt to font size or character dimensions:

  • em → relative to the element’s own font-size.

Code Block Loading...

  • rem → relative to the root (html) font size.

Code Block Loading...

  • ex → relative to the height of the lowercase “x” in the font.
  • ch → relative to the width of the “0” (zero) character.

Viewport Units

Viewport units scale with the browser window size:

  • vw → 1% of viewport width
  • vh → 1% of viewport height
  • vmin → 1% of the smaller dimension (width or height)
  • vmax → 1% of the larger dimension

Example:

Code Block Loading...

Fraction Units (fr)

Used in CSS Grid to divide space into fractions.

Example:

Code Block Loading...

Example

Code Block Loading...

Key Takeaways

  • Absolute units (px, cm, in) are fixed.
  • Relative units (em, rem, %, ch, ex) adapt to context.
  • Viewport units (vw, vh, vmin, vmax) scale with the browser window.
  • Fraction units (fr) are unique to CSS Grid.