Lesson 2
px, rem, and em
Choose the right unit for design handoff, component scaling, and nested typography.
These three units appear in almost every frontend codebase. They look interchangeable in small examples, but they behave differently in real components.
px: the design handoff default
px is an absolute CSS unit. 16px means sixteen CSS pixels regardless of parent font-size.
Use px when:
- Matching a fixed border, shadow, or hairline divider
- Working with canvas, SVG stroke widths, or pixel-perfect assets
- Translating a one-off spec where rem tokens are not defined yet
Avoid using px for all typography if your design system expects rem-based scaling.
rem: relative to the root element
1rem equals the computed font-size of the root element (html), usually 16px by default.
html {
font-size: 16px;
}
.title {
font-size: 1.5rem; /* 24px */
}
Use rem when:
- Building design tokens for font-size, spacing, and radius
- You want sizes to scale if the project changes root font-size
- You need consistent values across unrelated components
em: relative to the current element's font-size
1em equals the element's own computed font-size (or the parent's for properties like padding in some inheritance cases).
.button {
font-size: 1rem;
padding: 0.75em 1.25em;
}
Here padding scales with button font-size automatically.
Use em when:
- Spacing should follow local typography inside a component
- Icons or badges should scale with nearby text
- You intentionally want nested sizing behavior
Quick comparison
| Unit | Best for | Watch out for |
|---|---|---|
| px | Borders, precise assets | Does not scale with root settings |
| rem | Global tokens, typography | Assumes stable root font-size |
| em | Component-internal rhythm | Compounds in deeply nested text |
Common mistake: mixing contexts
A designer gives 20px body text. You write 20px in CSS. Later the team switches to html { font-size: 62.5%; } for easier rem math, and your px values no longer align with rem tokens.
Better workflow: convert px to rem once, store tokens, and reuse them.
Key takeaway
Use px for fixed physical details, rem for system-wide tokens, and em for sizes that should follow local text.
Convert design px to rem with the CSS Unit Converter / Clamp Generator and set root font-size to match your project before copying values.