rem vs em in CSS
🔹 The Core Difference
em= relative to the parent element’s font-sizerem= relative to the root (html) font-size
🧠 Mental Model
Think of it like this:
em→ local scaling (inherits context)rem→ global scaling (anchored to root)
📏 Example Setup
html {
font-size: 16px;
}
.parent {
font-size: 20px;
}
.child {
font-size: 2em;
}
.child-rem {
font-size: 2rem;
}
What happens:
.child→2em→ 2 × parent (20px) = 40px.child-rem→2rem→ 2 × root (16px) = 32px
🔁 The “Compounding Problem” (why em can bite you)
.parent {
font-size: 1.5em;
}
.child {
font-size: 1.5em;
}
If root = 16px:
.parent→ 1.5 × 16 = 24px.child→ 1.5 × 24 = 36px
👉 This stacks exponentially as you nest deeper.
That’s where people get burned.
🎯 When to Use Each
✅ Use rem (most of the time)
- Typography system (headings, body text)
- Layout spacing (margin, padding)
- Consistent scaling across app
👉 Why:
- Predictable
- Easy to reason about
- One change at
htmlscales everything
✅ Use em (when you want locality)
- Components that should scale with parent
- Buttons, cards, modular UI pieces
- Icon sizing relative to text
👉 Example:
.button {
font-size: 1rem;
padding: 0.5em 1em; /* scales with button text */
}
🔧 Pro Pattern (what most solid systems do)
html {
font-size: 16px; /* or 62.5% trick → 10px base */
}
/* Use rem for layout + typography */
h1 { font-size: 2rem; }
p { font-size: 1rem; }
/* Use em inside components */
.button {
font-size: 1rem;
padding: 0.5em 1em;
}
👉 This gives:
- Global consistency (
rem) - Local flexibility (
em)
⚠️ Common Gotchas
1. “Why is everything huge??”
→ You used em inside nested elements → compounding
2. “Why didn’t this scale with the component?”
→ You used rem where em was intended
3. Mixing both randomly
→ leads to non-linear scaling chaos
🧠 Quick Heuristic (honestly this is enough)
- If you’re thinking “system-wide” → use
rem - If you’re thinking “relative to this thing” → use
em
🔥 One-Liner Summary
remis stable.emis contextual.