Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

px, em, rem, %, vw, vh

Units for lengths in CSS: absolute pixels and relative units.

Syntax

16px 1.5rem 2em 50% 100vw 100dvh

Parameters

ParameterTypeDescription
pxabsoluteA CSS pixel; the same on all screens regardless of density.
emrelativeThe font size of the element itself (for `font-size` — of the parent).
remrelativeThe font size of the root `<html>`, usually 16px.
%relativeA percentage of the parent's size (what exactly depends on the property).
vw | vhviewport1% of the window width or height.
dvh | svhviewport1% of the window height, taking the changing mobile toolbar into account.
chrelativeThe 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

  • font-size — The size of the font.
  • clamp() — Keeps a value within limits: the preferred value, but not less than the minimum and not more than the maximum.
  • calc() — Calculates a value from an expression — even with mixed units.
  • width — The width of an element.

Related recipes

In the tutorial

  • Units — Pixels, percentages, em, rem and viewport units — how they differ and when to use which.

Thanks for reading!

Donate to the site — we work hard for you.