Fluid typography with clamp() in CSS
33 A type scale with clamp
hardSize a heading so it grows with the viewport between a floor and a ceiling, using one declaration and no breakpoints. Then work out what it resolves to at three widths.
Stuck? Three hints, smallest first
- 1.
clamp(min, preferred, max): the preferred value is used unless it falls outside the bounds. - 2. The preferred value must include a
remterm, not justvw, or the text stops responding to browser zoom. - 3.
0.9rem + 0.9vwat a 320px viewport is 14.4px plus 2.88px, which is under the floor.
<h2 class="fluid">Departures</h2>
<p class="body">Body copy stays at a fixed size, so the contrast in scale is visible.</p>
.fluid {
/* floor 18px, preferred 0.9rem + 0.9vw, ceiling 32px */
font-size: clamp(1.125rem, 0.9rem + 0.9vw, 2rem);
line-height: 1.2;
margin: 0 0 8px;
}
.body {
font-size: 0.9rem;
line-height: 1.6;
margin: 0;
max-width: 46ch;
color: #5c5c66;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// What clamp() resolves to, given a root size and a viewport width.
const ROOT = 16;
const preferred = (vw) => 0.9 * ROOT + 0.9 * (vw / 100);
const resolve = (vw) => Math.min(Math.max(preferred(vw), 1.125 * ROOT), 2 * ROOT);
const round = (n) => Math.round(n * 100) / 100;
test('the floor is 18px and the ceiling 32px', [1.125 * ROOT, 2 * ROOT], [18, 32]);
test('at 320px the preferred value is under the floor', round(preferred(320)), 17.28);
test('so the floor is used', resolve(320), 18);
test('at 1200px it sits between the bounds', round(resolve(1200)), 25.2);
test('at 2400px it is capped at the ceiling', resolve(2400), 32);
test('one declaration, no breakpoints', /@media/.test(css), false);
test('the preferred value includes a rem term, so zoom still works', /clamp\([^)]*rem \+ [\d.]+vw/.test(css), true);
test('and it is not vw alone', /clamp\(\s*[\d.]+rem,\s*[\d.]+vw/.test(css), false);
Output
The last two checks are the accessibility part, and they are the reason this is marked hard. A preferred value of pure vw makes the text depend on the window and nothing else, so a reader who zooms to 200% gets exactly the same pixel size — the text simply refuses to grow. Including a rem term keeps the reader’s own font size in the sum. The floor matters for the same reason: without one, a narrow window can shrink a heading below body copy. The arithmetic here is the browser’s, done by hand, because there is no viewport in the build to measure.