Units & Sizing

CSS lengths can be absolute (pixels) or relative — to the font size, to the parent, or to the viewport. Choosing the right unit is the difference between a design that adapts gracefully to different screens and text sizes, and one that breaks.

Pixels

Try it yourself
Result

A CSS pixel (px) is a fixed reference unit, not a physical screen pixel — on high-density screens, one CSS pixel covers several device pixels. Pixels are fine for borders, shadows and small details, but fixed widths don't adapt to the screen or to users who enlarge text.

Font-relative units: em and rem

Try it yourself
Result
  • rem is relative to the root (<html>) font size — 16px by default. Predictable, and it scales when users change their browser's text size. The usual choice for font sizes and spacing.
  • em is relative to the element's own font size (for font-size itself, the parent's). Great when something should scale with its text — like a button's padding — but nested em font sizes compound.
Try it yourself
Result

Percentages

Try it yourself
Result

Percentages are relative to something on the parent — width to the parent's width, font-size to the parent's font size. Surprisingly, vertical padding and margin percentages are also relative to the parent's width.

Viewport units

Try it yourself
Result
UnitRelative to
vw, vh1% of the viewport width / height
vmin, vmax1% of the smaller / larger viewport side
svh, lvh, dvhSmall, large and dynamic viewport height — handle mobile browser toolbars that appear and disappear

On phones, 100vh can be taller than the visible area when the address bar is showing. Use 100dvh for full-screen sections that should exactly fit what's visible.

Other useful units

UnitMeaningTypical use
chWidth of the "0" charactermax-width: 65ch for readable line lengths
ex, cap, lhHeight of x / capital letters; line heightAligning icons with text
frFraction of free space in a gridGrid columns (lesson 29)
cqi, cqwPercentage of a container's sizeContainer queries (lesson 33)
deg, turn, s, msAngles and timesTransforms, animations

Min and max sizes

Try it yourself
Result

min-width, max-width, min-height and max-height set limits rather than exact sizes. "Fluid up to a maximum" (width: 90%; max-width: …) is one of the most common responsive patterns. Prefer min-height over fixed height for boxes containing text, so content never overflows.

Intrinsic sizing keywords

Try it yourself
Result

Choosing units

For…Prefer
Font sizesrem (or clamp() with rem/vw for fluid type)
Spacing (margin, padding, gap)rem, or em when it should follow the text
Widths of layout areas%, fr, with max-width in rem or ch
Borders, hairlines, shadowspx
Full-screen sectionsdvh / svh
Line heightUnitless numbers: 1.5

Try it yourself

Try it yourself
Result