Build fluid typography with clamp()
Pick two viewport widths and two font sizes, work out the vw slope and rem intercept by hand, and clamp() holds the size between them.
You set a heading to font-size: 4vw so it would grow with the window. At 320px wide it renders at 12.8px, smaller than your body text, and at 1600px it renders at 64px. A bare vw value has no floor and no ceiling.
Pick two points
clamp() takes a minimum, a preferred value and a maximum. The preferred value is a line that grows with the viewport, and clamp() holds the result between the other two. You need that line's slope and intercept.
Choose two points: 16px at a 400px viewport and 32px at a 1200px viewport. Then do three steps by hand, no preprocessor required.
- Divide the size range by the width range. 16px over 800px is 0.02.
- Multiply by 100 to get the
vwvalue, because 1vw is 1% of the width. That gives 2vw. - Multiply the slope by the minimum width (0.02 times 400 is 8px) and subtract that from the minimum size. The remainder is the intercept: 8px, which is 0.5rem at a 16px root.
h1 {
font-size: clamp(1rem, 0.5rem + 2vw, 2rem);
}With a 16px root, the middle term equals 16px at a 400px viewport and 32px at 1200px. A different root font size shifts those breakpoints.
Check both ends
Computed styles settle it faster than reading the formula. With playwright and its Chromium browser installed, save this as an .mjs file and run it with Node.
import { chromium } from 'playwright'
const browser = await chromium.launch()
const html = `<style>h1 { font-size: clamp(1rem, 0.5rem + 2vw, 2rem); }</style><h1>Fluid heading</h1>`
for (const width of [320, 400, 800, 1200, 1600]) {
const page = await browser.newPage({ viewport: { width, height: 800 } })
await page.setContent(html)
console.log(width, await page.evaluate(() => getComputedStyle(document.querySelector('h1')).fontSize))
}
await browser.close()
// prints 320 16px, 400 16px, 800 24px, 1200 32px, 1600 32pxAt 800px, the heading is 24px, halfway between the two sizes.
The outer rows come from the clamps. At 320px the middle term is 0.5rem plus 6.4px, which is 14.4px, so clamp() returns the 1rem floor. At 1600px it is 40px, so the 2rem ceiling wins.
Try the heading at 200% browser zoom and with a larger default font size. The viewport term can shrink in CSS pixels as you zoom, so rem bounds alone don’t guarantee that text doubles in size.