Selecting the proper CSS unit of measurement is the single most vital factor in crafting scalable, accessible, and responsive user interfaces. Using rigid pixel values everywhere breaks accessibility for visually impaired users; mastering relative and dynamic viewport units ensures flawless responsiveness across everything from smartwatch dials to 4K widescreen displays.
Pixels (px) are tied to physical screen device dots (1px = 1/96th of an inch). While pixels provide predictable, millimeter-precise layout dimensions, they fail accessibility standards when applied to typography because they refuse to scale if a user adjusts their browser's default font size.
| Unit | Relative To What? | Default Value (16px base) | Compounding Effect? | Best Practice Use Case |
|---|---|---|---|---|
| rem (Root EM) |
The root <html> element's font size. |
1rem = 16px1.5rem = 24px |
No (Predictable and constant across the entire document) | Typography font sizes, padding, margins, layout containers. |
| em (Local EM) |
The font size of the immediate parent element. | Inherited parent size | Yes! Nested elements multiply exponentially (e.g., 2em inside 2em = 4em) | Component-relative padding (e.g., button icons scaling with button text). |
Viewport units scale dynamically with the browser window dimensions:
1vw: 1% of the viewport width.
1vh: 1% of the viewport height.
On mobile devices (iOS Safari, Android Chrome), setting a hero section to height: 100vh caused content to be covered by the browser's dynamic URL search bar. Modern CSS introduced three new viewport units to fix this:
• svh (Small Viewport Height): Viewport height when browser UI bars are expanded.
• lvh (Large Viewport Height): Viewport height when browser UI bars are collapsed.
• dvh (Dynamic Viewport Height): Dynamically updates in real-time as the user scrolls! Use height: 100dvh; for full-screen hero sections on mobile.
Question: If the root HTML font size is 16px, and a <div> has font-size: 1.25rem; with margin: 2rem;, calculate the pixel values applied by the browser engine.
Answer:
• Font Size: 1.25 × 16px = 20px.
• Margin: 2 × 16px = 32px.
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.