CSS Reference ยท Units and Values
The em unit
Reference for the CSS em unit: how it relates to the element's font size, why font-size em values compound when nested, and when em beats rem.
em is a length unit that equals the computed font size of the element it is used on. If an element has font-size: 20px, then 1.5em means 30px for its padding, margins, width and any other length. Because the value follows the font size, components that use em scale as a whole when you change the text size.
There is one special case. In the font-size property itself, em refers to the parent's font size, since an element cannot be relative to its own size while that size is being computed.
.button { font-size: 1.25rem; padding: 0.5em 1em; }
Try it
Only font-size changes between the three buttons. Padding, border width and radius are all in em, so they scale in proportion.
Each nested <ul> multiplies the already-multiplied size by 1.25. This is the main trap of em for font sizes.
Syntax
<length> = <number>em
- Reference: the element's computed
font-size(the parent's, when used infont-size). - Applies to: any property that accepts a
<length>. - Animatable: yes, as part of a length.
- In media queries:
emequals the browser's initial font size (normally 16px), not any author-set size.
Values
| Value | Description |
|---|---|
1em |
The element's font size. |
0.5em |
Half of it. |
2em in font-size |
Twice the parent's font size. |
2em in other properties |
Twice the element's own font size. |
Usage notes
- Use for component-internal spacing. Padding and gaps in buttons, badges and inputs look balanced at any text size when written in
em. - Avoid for nested font sizes. Compounding is hard to follow. Use
remforfont-sizeandemfor the spacing around it. - Zero needs no unit.
0is the same as0em. - Changing font-size moves everything. If you set both
font-sizeand anemmargin on the same element, the margin is computed from the new size. - Accessibility.
emrespects the user's default font size when the chain starts from a relative root size. - Related unit.
ch,exandlhare also font-relative but use glyph metrics or line height.
Browser support
Supported in every browser.
Related
remโ relative to the root font sizepxโ the pixel unitch,ex,lhand friends โ glyph-based unitsfont-sizeโ the property that sets the base- Lesson: CSS Units