CSS units can be confusing. You’ve got px, rem, em, and a dozen others. Which one should you use?
Here’s the deal:
Each unit serves a different purpose. Understanding them will level up your CSS game.
px — The Absolute Unit
Pixels (px) are the most straightforward unit. One pixel equals one dot on your screen.
.box {
width: 200px;
padding: 16px;
font-size: 14px;
}
Pros:
- Precise control
- Easy to understand
- What you see is what you get
Cons:
- Doesn’t scale with user preferences
- Can break accessibility
When to use px:
- Border widths
- Box shadows
- Small decorative elements
rem — The Root-Relative Unit
rem stands for “root em”. It’s relative to the root element’s (<html>) font size.
By default, browsers set the root font size to 16px. So:
1rem=16px1.5rem=24px0.875rem=14px
html {
font-size: 16px; /* browser default */
}
.card {
padding: 1.5rem; /* 24px */
font-size: 1rem; /* 16px */
margin-bottom: 2rem; /* 32px */
}
Want to know the best part?
If a user changes their browser’s default font size, everything scales proportionally. This is huge for accessibility.
Pro tip: Need to convert pixel values to rem? Use an online px to rem converter to speed up your workflow.
em — The Parent-Relative Unit
em is relative to the parent element’s font size. This is where things get tricky.
.parent {
font-size: 20px;
}
.child {
font-size: 1.5em; /* 30px (20 × 1.5) */
padding: 1em; /* 30px (relative to its own font-size!) */
}
It gets worse:
em compounds. Nested elements multiply their sizes:
.level-1 { font-size: 1.2em; } /* 19.2px */
.level-2 { font-size: 1.2em; } /* 23.04px */
.level-3 { font-size: 1.2em; } /* 27.65px */
This compounding can quickly spiral out of control.
When to use em:
- Component-level spacing (padding/margin relative to text size)
- Button padding
- Icon sizing next to text
Quick Comparison
| Unit | Relative to | Scales with user prefs | Use case |
|---|---|---|---|
px | Nothing (absolute) | ❌ | Borders, shadows |
rem | Root font size | ✅ | Typography, spacing |
em | Parent font size | ✅ | Component spacing |
The Bottom Line
Here’s my recommendation:
-
Use
remfor typography and layout spacing — It respects user preferences and keeps your design consistent. -
Use
emfor component-internal spacing — Buttons, cards, and other components that should scale with their text. -
Use
pxsparingly — Only for things that should stay fixed regardless of zoom level.
This approach gives you the best of all worlds: precise control where you need it, accessibility where it matters.
Now go refactor those hardcoded pixel values!