Values and visual language

Length units

Choose pixels, rems, ems, percentages, viewport units, and character units according to what a size should respond to.

8 minute lesson

~~~

CSS units express relationships.

  • px is a CSS reference pixel, not a guaranteed physical device pixel.
  • rem is relative to the root font size.
  • em follows font size: on font-size it uses the parent; on many other properties it uses the element’s computed font size.
  • % depends on the property and its containing block.
  • vw and vh relate to viewport dimensions.
  • ch approximates the width of the 0 glyph and is useful for readable line lengths.
.article {
  width: min(100% - 2rem, 65ch);
  margin-inline: auto;
}

There is no universally best unit. Ask what the value should track: user text preferences, its component, its container, or the viewport.

Viewport height needs extra care on mobile. Browser controls can expand and collapse. svh represents the small viewport, lvh the large viewport, and dvh updates with the dynamic viewport. A fixed 100vh panel can hide content behind browser UI; prefer content-driven min-height, then choose the viewport variant that matches the experience.

Percentages are deliberately contextual. width: 50% relates to the containing block’s width, while percentage padding also resolves against the containing block’s inline size. Inspect the used pixel value in DevTools instead of assuming every percentage uses the same reference.

Resize, zoom to 200%, and increase the default font size. Values chosen for the correct relationship should adapt without clipping text or forcing horizontal scrolling.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →