CSS Tutorial · CSS Basics · Lesson 8 of 19

CSS Units

px, %, em, rem, vw, vh and clamp() — when to use which.

Absolute and relative units

Unit Relative to
px a CSS pixel
% the parent's size
em the element's own font size
rem the root (<html>) font size — usually 16px
vw / vh 1% of the viewport width / height
ch the width of the "0" character

Use rem for font sizes and spacing (respects the user's browser font settings), % and fr for layouts, ch for readable line lengths (max-width: 65ch).

clamp()

clamp(min, preferred, max) creates fluid values — a heading that grows with the screen but stays within limits:

Example 1Try it yourself
<style>
  body { font-family: system-ui, sans-serif; }
  .rem { font-size: 1.25rem; }
  .em-parent { font-size: 20px; }
  .em-parent span { font-size: 1.5em; }
  .fluid { font-size: clamp(1rem, 5vw, 2.5rem); color: #2563eb; }
  .narrow { max-width: 30ch; background: #f1f5f9; }
  .calc { width: calc(100% - 40px); background: #dcfce7; }
</style>
<p class="rem">1.25rem = 20px with the default 16px root</p>
<p class="em-parent">Parent 20px, <span>span 1.5em = 30px</span></p>
<p class="fluid">clamp() heading — resize the window</p>
<p class="narrow">This paragraph is limited to about thirty characters per line.</p>
<div class="calc">calc(100% - 40px)</div>

calc() mixes units: width: calc(100% - 2rem).

Test yourself

Which unit is relative to the root element's font size?

  1. em
  2. rem
  3. px
  4. vh
Show answer

Answer: rem