CSS offers different units for sizing elements:
px(pixels)- Absolute unit.
- 1px = 1 screen pixel.
- Does not scale with parent or root font size.
-
Example:
p { font-size: 16px; }
em- Relative to the font size of the parent element.
- Can compound when nested, as it multiplies by the parent’s size.
-
Example:
div { font-size: 20px; } p { font-size: 1.5em; /* 1.5 * 20px = 30px */ }
rem(root em)- Relative to the root
<html>font size, usually 16px by default. - Independent of parent font size → more predictable than
em. -
Example:
html { font-size: 16px; } p { font-size: 2rem; /* 2 * 16px = 32px */ }
- Relative to the root
🔹 Key Differences
| Unit | Relative To | Compounds? | Use Case |
|---|---|---|---|
| px | Absolute pixels | No | Precise control |
| em | Parent element’s font size | Yes | Relative sizing inside containers |
| rem | Root <html> font size |
No | Consistent sizing across page |
💡 Example Use
html {
font-size: 16px; /* 1rem = 16px */
}
h1 {
font-size: 2rem; /* 32px */
}
p {
font-size: 1em; /* inherits parent size */
}
div {
font-size: 1.5em; /* scales based on parent */
}
In short:
px→ fixed sizeem→ relative to parentrem→ relative to root (more predictable for responsive design)