For a long time in my career, I used px (pixels) for everything in CSS. It felt precise, predictable, and easy to control. But recently, I’ve changed my mind. I’ve surrendered to rem and em after realizing their true power. Now, I barely touch px unless I absolutely have to. Here’s why.
The Problem with px
At first, pixels seem like the best unit of measurement. Set a button to 50px, and it will always be 50px. But that’s exactly the problem—px is too rigid. It doesn’t adapt well to different screen sizes, zoom levels, or user preferences. This means:
- Users who increase their browser’s font size for accessibility won’t see the changes.
- Responsive designs require constant media queries to adjust fixed pixel values.
- Maintaining a consistent, scalable design across devices becomes harder.
The Superpower of rem and em
Once I fully understood rem and em, I realized they solve all these issues beautifully.
rem (Root Em)
- rem is relative to the root font size (html { font-size: 16px; } means 1rem = 16px).
- If a user changes their browser’s default font size, everything using rem scales accordingly.
- Want to scale everything up or down? Just change the root font size.
Example:
button {
font-size: 1.25rem; /* Scales with the root font size */
padding: 0.5rem 1rem;
}
em (Relative to Parent)
- em is relative to the font size of its parent element.
- Great for keeping elements proportional inside components.
- Nested em values can multiply, which can be useful (or tricky if not careful).
Example:
.card {
font-size: 1.2em;
}
.card button {
font-size: 0.9em; /* Relative to .card's font size */
}
Where I Still Use px
Though I avoid px for most things, I still use it for:
- Borders (1px is fine because borders shouldn’t scale unpredictably).
- Box shadows (for a consistent appearance).
- Media queries (though em and rem work, many browsers handle px better).