CSS · Course navigation

CSS Units and Fluid Typography

Choose relative units and clamp() so text scales with the user's settings and the screen.

On this page

The concept

px is a fixed size, while rem is relative to the root font size, so layouts that use rem grow when users increase their browser's text size. em is relative to the current element's font size, which suits icons that should scale with their text. ch is the width of the 0 character, so max-width: 65ch keeps lines at a readable length. clamp(min, preferred, max) picks a fluid value between two limits, for example a heading that grows with the viewport width but never gets too small or too large. A unitless line-height scales with the font size.

Code example

CSS
html { font-size: 100%; }
body {
  font-family: system-ui, sans-serif;
  line-height: 1.5;
  max-width: 65ch;
  margin-inline: auto;
  padding: 1rem;
}
h1 { font-size: clamp(1.75rem, 4vw, 2.5rem); }
.icon { width: 1.5em; height: 1.5em; }

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1html { font-size: 100%; }
2body {
3 font-family: system-ui, sans-serif;
4 line-height: 1.5;
5 max-width: 65ch;
6 margin-inline: auto;
7 padding: 1rem;
8}
9h1 { font-size: clamp(1.75rem, 4vw, 2.5rem); }
10.icon { width: 1.5em; height: 1.5em; }

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Keep the root size at the user's browser setting. Do not force 16px.—
—
A unitless line height is multiplied by each element's own font size.—
—
About 65 characters per line is comfortable to read.—
—
Centers the block horizontally using logical properties that also work for right-to-left text.—
—
The heading is 4% of the viewport width, but never smaller than 1.75rem or larger than 2.5rem.—
—
em makes the icon scale with the font size of the text around it.—
—

Behind the scenes

How CSS processes this code

The browser matches selectors, computes styles, and paints the result. CSS does not produce console output.