CSSBasic
What is the difference between px, em, and rem in CSS?
The Three Units Defined
px (Pixels)
- An absolute unit — 1px equals one logical pixel on the screen
- Not affected by parent or root element font sizes
- On high-DPI (Retina) displays, 1px may correspond to multiple physical pixels
em
- A relative unit — relative to the current element's font size
- If not set on the current element, it inherits from the parent
- Can compound unexpectedly in deeply nested elements
/* Parent font-size: 16px */
.parent { font-size: 16px; }
/* Child: 1em = 16px, 2em = 32px */
.child { font-size: 2em; } /* = 32px */
/* Grandchild: 1em = 32px */
.grandchild { font-size: 1.5em; } /* = 48px — keeps growing! */
rem (Root em)
- A relative unit — relative to the root element (
<html>) font size - Browser default is
html { font-size: 16px } - Not affected by nesting, making it more predictable and maintainable
html { font-size: 16px; }
.title { font-size: 2rem; } /* = 32px, always relative to html */
.text { font-size: 1rem; } /* = 16px */
When to Use Each?
| Use Case | Recommended Unit |
|---|---|
| Fixed sizes (border, shadow) | px |
| Font sizes (responsive design) | rem |
| Component-internal spacing (relative to component font) | em |
| Overall responsive layout scaling | rem |
Modern best practice: Use
remfor fonts and most spacing; useemonly when you intentionally want sizing relative to the parent element.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
