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 */- The nested markup makes inheritance and relative sizing visible.
- Each 1.5em font-size is based on its parent’s computed font size, producing 30px then 45px here.
- Inspect computed font-size or edit an ancestor size to compare em and rem.
HTML used by this example
<div class="parent">Parent: 20px<div class="child">Child: 1.5em<div class="grandchild">Grandchild: 1.5em</div></div></div>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 */
}- The nested markup makes inheritance and relative sizing visible.
- The sample sets a 16px root; 1.5rem therefore produces 24px regardless of the intermediate font sizes.
- Inspect computed font-size or edit an ancestor size to compare em and rem.
HTML used by this example
<div style="font-size:12px">Small ancestor<div style="font-size:30px">Large ancestor<div class="deeply-nested-element">1.5rem still uses the root</div></div></div>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
Browser compatibility
- chrome
- Yes
- firefox
- Yes
- safari
- Yes
- edge
- Yes
These are the existing reference’s support labels, not tested minimum versions. Individual values and APIs can have different support. Check the linked specification before choosing a browser target.
CSS specifications (modules)