When do you use rem vs em vs px units?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
rem scales with the root font-size — ideal for spacing, sizes, breakpoints (respects user preferences). em compounds relative to the local context — good for component-relative padding. px is absolute — fine for hairlines/shadows, problematic for typography at scale.
Detailed explanation
Unit choice encodes intent. rem anchors everything to html's font-size (default 16px): setting paddings, widths, media queries in rem means users who raise browser font size scale your entire layout proportionally — core accessibility behavior. em references the current element's computed font-size, compounding through nesting: powerful inside components (padding proportional to label text) but notorious for unexpected inheritance drift. px stays constant regardless of user settings — acceptable for sub-pixel borders, shadows, icon alignment where scaling harms crispness, risky for text since it ignores zoom-based accessibility on some browsers. Modern practice: typography/spacing/layout in rem, component-internal relationships in em where deliberate, pixels only for decorative detail. Also relevant: ch (character width) for input sizing, dvh/svh for mobile viewport height stability, clamp() fluid type bridging min/max without breakpoints.
Example
:root { font-size: 100%; } /* 16px base */
.card {
padding: 1.5rem; /* scales with root */
border: 1px solid #ddd; /* crisp hairline */
max-width: 40ch; /* readable line length */
}
.badge {
font-size: 0.75em; /* relative to parent text */
padding-inline: 0.75em; /* grows with its own font */
}
h1 { font-size: clamp(2rem, 5vw, 3.5rem); }Interview tip
Frame each unit by what should scale when the user changes settings. Mention clamp() and dvh briefly — current-practice signals interviewers notice.
Common mistakes
- Saying px is always bad — hairline borders are legit.
- Not understanding em compounding through nested elements.