Units

px, em, rem, %, vw — When to Use Each

Units

CSS has absolute and relative units. Pick the right one for the context — `rem` for type, `px` for borders, `%` and `vw` for responsive sizing.

4 min read Level 2/5 #css#units#px
What you'll learn
  • Tell `em` from `rem`
  • Use viewport units (`vw`, `vh`)
  • Pick units by purpose

CSS values often have units. The unit matters as much as the number.

Absolute Units

UnitWhat
pxPixel — fixed in size regardless of font scale
ptPoints (1/72 inch) — print only
cm, mm, inPhysical units — print only

px is the default for the web. The others rarely come up.

Relative — Type

UnitRelative to
emThe current element’s font-size
remThe root element’s (<html>) font-size
%The parent (varies by property)
chThe width of “0” in the current font
exThe x-height of the current font

rem is the workhorse for typography. 1rem = whatever the user’s browser font-size is set to (defaults to 16px). Respecting it means users who set their browser font size larger get a proportionally larger UI.

html { font-size: 16px; }     /* base — usually leave at default */
h1   { font-size: 2rem; }     /* 32px */
p    { font-size: 1rem; }     /* 16px */
.note { font-size: 0.875rem; } /* 14px */

em vs rem

  • rem is always relative to the root. Predictable.
  • em is relative to the current element’s font-size. It compounds.
.card    { font-size: 1.2rem; }
.card h2 { font-size: 1.5em; } /* 1.5 × 1.2rem = 1.8rem */

Use em for properties that should scale with their element (like padding around text). Use rem for properties that should scale with the root.

Viewport Units — Responsive Sizing

UnitRelative to
vw1% of the viewport width
vh1% of the viewport height
vminThe smaller of the two
vmaxThe larger of the two
svh, lvh, dvhSmall/large/dynamic viewport (modern)

100vh is “the full viewport height”. 50vw is “half the viewport width”. Great for hero sections, fullscreen layouts, splash screens.

Percent

.col { width: 50%; }     /* half the parent's content width */

% means “of the parent”, but for which dimension depends on the property — padding: 5% is 5% of the parent’s width (even when applied to padding-top!).

When To Use Which

NeedUnit
Type sizingrem
Padding around textem
Fixed widths (borders, radii)px
Width relative to parent%
Full-bleed sectionsvw / vh / dvh
Width based on character countch (e.g., max-width: 70ch)

Up Next

Comments and how to organize CSS as it grows.

Organization →