CSS Units: px, rem, em
In CSS, various units of measurement are used to set sizes (margins, fonts, widths, etc.). Among them, especially important are: px, em, rem. They affect responsiveness, scalability and style inheritance.
px — pixels
- Absolute unit of measurement.
- Sets fixed size, independent of parent or root font.
- Doesn't adapt to scaling, poorly suited for responsive design.
font-size: 16px;
padding: 10px 20px;
- Suitable for pixel-perfect design
- Scales poorly and doesn't account for user settings
em — relative unit
- Relative to parent element's font size.
- 1em = current parent's font-size.
- Used for margins, padding and even font-size, but can behave unpredictably when nested.
/* parent */
.parent {
font-size: 16px;
}
/* child */
.child {
font-size: 1.5em; /* 24px relative to parent */
}
em nesting can accumulate:
.outer {
font-size: 16px;
}
.inner {
font-size: 1.2em; /* 16px × 1.2 = 19.2px */
}
.inner .text {
font-size: 1.2em; /* 19.2px × 1.2 = ~23px */
}
rem — root em
- Relative to root element's (html) font size.
- 1rem = font-size at
<html>level (16px by default). - Independent of parent, making rem more predictable.
html {
font-size: 16px;
}
.button {
font-size: 1.25rem; /* 20px */
padding: 0.5rem 1rem; /* 8px 16px */
}
- Convenient for responsive typography
- Works well with media queries
- Easy to scale (change 1 value in html — everything changes)
Comparison Table
| Unit | Relative to? | Scaling Support | Application |
|---|---|---|---|
px | Absolute pixel | ❌ | Fixed sizes |
em | Parent font-size | ✅ (but can accumulate) | Internal padding, margin |
rem | html font-size | ✅ | Text sizes, layout, everything |
When to use what?
px— when you need to fix size regardless of context (e.g., 1px icon).em— for component internal scalability (e.g., padding, margin).rem— for global typography, margins, responsive design.
Tip:
Use rem for base sizes, em — for component internal proportions, and px — only in extreme cases.