px, em, rem, %, vw, vh
Units for lengths in CSS: absolute pixels and relative units.
Syntax
16px 1.5rem 2em 50% 100vw 100dvhParameters
| Parameter | Type | Description |
|---|---|---|
| px | absolute | A CSS pixel; the same on all screens regardless of density. |
| em | relative | The font size of the element itself (for `font-size` — of the parent). |
| rem | relative | The font size of the root `<html>`, usually 16px. |
| % | relative | A percentage of the parent's size (what exactly depends on the property). |
| vw | vh | viewport | 1% of the window width or height. |
| dvh | svh | viewport | 1% of the window height, taking the changing mobile toolbar into account. |
| ch | relative | The width of the "0" character in the current font. |
Examples
The same block width in different units:
<style>
div { background: lightskyblue; margin-bottom: 6px; padding: 4px; }
</style>
<div style="width: 150px;">150px</div>
<div style="width: 50%;">50% of the parent</div>
<div style="width: 30vw;">30vw — 30% of the window width</div>
<div style="width: 12rem;">12rem — 12 page font sizes</div>
<div style="width: 20ch;">20ch — about 20 characters</div>Padding in em grows together with the button's font:
<div style="font-size: 20px;">
<button style="font-size: 0.8em; padding: 0.5em 1em;">em: grows with the font</button>
</div>Notes
A simple rule: rem for font sizes and spacing, px for thin borders, % and fr for layout, ch for line length. On phones 100vh may be taller than the visible area — use 100dvh.
See also
Related recipes
In the tutorial
- Units — Pixels, percentages, em, rem and viewport units — how they differ and when to use which.