Codectionary / Developer documentation / CSS

Length Units: px, %, em, rem

CSS offers several length units. px is an absolute, fixed unit. % is relative to the parent element. em is relative to the current element's font-size (compounding when nested). rem is relative to the root (html) element's font-size, avoiding the compounding problem of em, and is generally preferred for consistent, predictable sizing.

Syntax

value: Npx | N% | Nem | Nrem;

Examples

The Compounding Problem with em

Why em can produce unexpected results when nested.

.parent { font-size: 20px; }
.child { font-size: 1.5em; }  /* 30px - relative to parent's 20px */
.grandchild { font-size: 1.5em; } /* 45px! - relative to child's 30px, compounds */

rem Avoids Compounding

rem is always relative to the root, regardless of nesting depth.

html { font-size: 16px; } /* the reference point for ALL rem values */

.deeply-nested-element {
  font-size: 1.5rem; /* always 24px, no matter how deeply nested */
  padding: 1rem;      /* always 16px */
}

Parameters and values

  • px (absolute): Fixed pixel size, does not scale with user font preferences
  • % (relative): Relative to the parent element's corresponding value
  • em (relative): Relative to the current element's font-size, compounds when nested
  • rem (relative): Relative to the root html element's font-size, does not compound

Best practices

  • Use rem for font-size and most spacing, so everything scales correctly if a user changes their browser's base font size for accessibility
  • Use em specifically when you want a value to scale with its own element's font-size, like padding inside a button that should grow with its text
  • Avoid px for font-size specifically, since it ignores user accessibility preferences for text scaling
  • Use % for widths within a fluid, responsive container, but be aware % for font-size and most other properties refers to the parent, which can be less predictable than rem

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation