Skip to content
AgileLogics
6 min read

Units and Values

Prerequisites: Colors

Lengths in CSS always need a unit (except 0).

Absolute: px

px is a CSS pixel — a fixed reference size, not a physical screen pixel. High-density screens use two or three device pixels per CSS pixel. Other absolute units (cm, in, pt) are mostly for print.

Relative to font size: rem and em

  • rem — relative to the root (html) font size, 16 pixels by default. 1.5rem = 24px.
  • em — relative to the element's own font size (for font-size itself, the parent's).
<style>
  .card { font-size: 20px; padding: 1em; margin: 1rem; }
  .card .inner { font-size: 1.5em; padding: 1em; }
  .card .rem { font-size: 1.5rem; }
</style>
<div class="card">
  <div class="inner">Inner</div>
  <div class="rem">Rem</div>
</div>
<script>
  const s = sel => getComputedStyle(document.querySelector(sel));
  console.log(".card    font", s(".card").fontSize, "padding", s(".card").paddingTop, "margin", s(".card").marginTop);
  console.log(".inner   font", s(".inner").fontSize, "padding", s(".inner").paddingTop);
  console.log(".rem     font", s(".rem").fontSize);
</script>
.card    font 20px padding 20px margin 16px
.inner   font 30px padding 30px
.rem     font 24px

em compounds: .inner's 1.5em is 1.5 × 20 = 30px, and its padding of 1em is then 30px too. rem always refers back to the root, so it's predictable.

Use rem for font sizes — it respects the visitor's browser font size setting, which people with low vision rely on. Setting html { font-size: 10px } or using px for text overrides their choice. Our REM to PX converter helps.

Percentages

% is relative to something that depends on the property: width: 50% is half the containing block's width, font-size: 120% is relative to the parent's font size, and — surprisingly — padding and margin percentages are relative to the container's width, even for top and bottom.

Viewport units

  • vw / vh — 1% of the viewport's width / height.
  • dvh — 1% of the dynamic viewport height, which accounts for mobile browser toolbars appearing and disappearing. svh (smallest) and lvh (largest) are fixed alternatives.
  • vmin / vmax — the smaller / larger of vw and vh.
.hero { min-height: 100dvh; }

100vh on phones is often taller than the visible area; 100dvh fixes that.

Character units

  • ch — the width of the 0 character in the current font. max-width: 65ch gives a comfortable reading line.
  • lh — the element's line height.

Other value types

  • Numbers without units: line-height: 1.5, opacity: 0.8, z-index: 10.
  • Angles: 45deg, 0.5turn. Times: 200ms, 1.5s.
  • Keywords: auto, none, bold, center...
  • Functions: calc(100% - 2rem), url("bg.jpg"), var(--gap).

Practice

If the root font size is 16px and a button has font-size: 0.875rem; padding: 0.5em 1em;, what are its font size and padding in pixels?

Show solution

Font size: 0.875 × 16 = 14px. Padding uses em, relative to the button's own 14px: 7px top and bottom, 14px left and right.