CSS Units
px - absolute pixels
Fixed size - not affected by user font size preferences.
css
.border { border: 1px solid; } /* always 1 pixel */em - relative to parent font-size
css
.parent { font-size: 16px; }
.child { font-size: 1.5em; } /* 24px */
.nested { font-size: 1.5em; } /* 36px - compounds! */Compounding makes em tricky for font sizes but useful for spacing that should scale with the component's text.
rem - relative to root font-size
css
html { font-size: 16px; } /* root */
.any-element { font-size: 1.5rem; } /* always 24px, no compounding */rem is predictable - always relative to <html>, never compounds.
vh / vw - viewport units
css
.hero { height: 100vh; } /* full viewport height */
.sidebar { width: 25vw; } /* 25% of viewport width */dvh / svh / lvh - dynamic viewport units (modern)
css
/* accounts for mobile browser chrome (address bar) */
.hero { height: 100dvh; } /* dynamic viewport height */When to use which
| Unit | Best for |
|---|---|
px | Borders, shadows, media queries |
rem | Font sizes, consistent spacing |
em | Padding/margin that scales with component text |
vh / vw | Full-screen sections, viewport-relative sizing |
% | Fluid widths relative to parent |
Use
remfor font sizes and most spacing. Usepxonly for borders and very small fixed values. Avoidemfor font sizes due to compounding.
updated
did you know it?