CSS Units Deep Dive
15 min read
pxemremvwvhdvhfrchViewport UnitsAccessibility
Absolute vs. Relative Units
Choosing the right CSS unit is critical for responsive design and accessibility. Using px everywhere is the #1 mistake beginners make.
Complete Unit Reference
| Unit | Type | Relative To | Best For |
|---|---|---|---|
px | Absolute | Screen pixel | Borders, shadows, fine details |
em | Relative | Parent font-size | Component-scoped sizing |
rem | Relative | Root font-size (html) | Font sizes, spacing (accessibility ✅) |
% | Relative | Parent element | Widths, fluid layouts |
vw | Relative | Viewport width | Full-width sections |
vh | Relative | Viewport height | Hero sections (⚠️ mobile issues) |
dvh | Relative | Dynamic viewport height | Mobile-safe full height |
svh | Relative | Smallest viewport height | Conservative full height |
lvh | Relative | Largest viewport height | Maximum full height |
vmin | Relative | Smaller of vw/vh | Responsive squares |
vmax | Relative | Larger of vw/vh | Filling larger dimension |
ch | Relative | Width of "0" character | Limiting text width (65ch) |
fr | Relative | Free space in grid | Grid column/row sizing |
Why rem for Font Sizes?
When users change their browser's default font size (for accessibility), px values don't scale. rem values do, because they're relative to the root font size.
This is a WCAG accessibility requirement. Using px for font sizes fails accessibility audits.
The Mobile vh Problem
On mobile browsers, 100vh includes the area behind the address bar, causing content to be hidden. Use 100dvh (dynamic viewport height) instead, which accounts for the browser chrome.