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.
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
| Unit | What |
|---|---|
px | Pixel — fixed in size regardless of font scale |
pt | Points (1/72 inch) — print only |
cm, mm, in | Physical units — print only |
px is the default for the web. The others rarely come up.
Relative — Type
| Unit | Relative to |
|---|---|
em | The current element’s font-size |
rem | The root element’s (<html>) font-size |
% | The parent (varies by property) |
ch | The width of “0” in the current font |
ex | The 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
remis always relative to the root. Predictable.emis 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
| Unit | Relative to |
|---|---|
vw | 1% of the viewport width |
vh | 1% of the viewport height |
vmin | The smaller of the two |
vmax | The larger of the two |
svh, lvh, dvh | Small/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
| Need | Unit |
|---|---|
| Type sizing | rem |
| Padding around text | em |
| Fixed widths (borders, radii) | px |
| Width relative to parent | % |
| Full-bleed sections | vw / vh / dvh |
| Width based on character count | ch (e.g., max-width: 70ch) |
Up Next
Comments and how to organize CSS as it grows.
Organization →