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
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
remis 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.emis relative to the element's own font size (forfont-sizeitself, the parent's). Great when something should scale with its text — like a button's padding — but nestedemfont sizes compound.
Percentages
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
| Unit | Relative to |
|---|---|
vw, vh | 1% of the viewport width / height |
vmin, vmax | 1% of the smaller / larger viewport side |
svh, lvh, dvh | Small, 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
| Unit | Meaning | Typical use |
|---|---|---|
ch | Width of the "0" character | max-width: 65ch for readable line lengths |
ex, cap, lh | Height of x / capital letters; line height | Aligning icons with text |
fr | Fraction of free space in a grid | Grid columns (lesson 29) |
cqi, cqw | Percentage of a container's size | Container queries (lesson 33) |
deg, turn, s, ms | Angles and times | Transforms, animations |
Min and max sizes
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
Choosing units
| For… | Prefer |
|---|---|
| Font sizes | rem (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, shadows | px |
| Full-screen sections | dvh / svh |
| Line height | Unitless numbers: 1.5 |