Picking the right CSS unit affects accessibility, responsiveness, and how predictable your layout is — and the differences between px, rem, em, and viewport units are more consequential than they first appear.
html { font-size: 16px; } /* the root, what rem is relative to */
.fixed-icon {
width: 24px; /* px: absolute, ignores user font-size preferences */
}
.readable-text {
font-size: 1rem; /* rem: relative to the ROOT font-size - predictable, respects zoom/accessibility settings */
margin-bottom: 1.5rem;
}
.component-padding {
padding: 1em; /* em: relative to the CURRENT element's font-size - compounds when nested */
}
.hero {
height: 60vh; /* viewport units: relative to viewport height/width */
font-size: clamp(1.5rem, 4vw, 3rem); /* fluid, scales with viewport, but clamped */
}
Prefer rem for font sizes and spacing (respects the user’s browser zoom and accessibility font-size settings, which plain px does not), em when you specifically want a value to scale with its parent’s font size, and viewport units for things that should genuinely respond to screen size.