CSS clamp() Fluid Typography: The Math Without the Headache
Fluid typography used to mean a pile of media queries. With clamp() you get a font size that scales smoothly between a minimum and maximum in one line. The catch is the math: the middle value mixes rem and vw, and gettin
Fluid typography used to mean a pile of media queries. With clamp() you get a font size that scales smoothly between a minimum and maximum in one line. The catch is the math: the middle value mixes rem and vw, and getting it wrong breaks zoom and accessibility.
The syntax
h1 {
font-size: clamp(1.5rem, 1rem + 2.5vw, 3rem);
}
-
Minimum (
1.5rem): the size never goes below this. -
Preferred (
1rem + 2.5vw): scales with the viewport. -
Maximum (
3rem): the size never goes above this.
How to compute the preferred value
Say you want 16px at a 320px viewport and 32px at a 1280px viewport.
- Slope = (32 - 16) / (1280 - 320) = 0.016667, which is 1.6667vw.
- Intercept = 16 - 0.016667 x 320 = 10.667px = 0.6667rem.
- Result:
clamp(1rem, 0.6667rem + 1.6667vw, 2rem).
Mistakes that bite
-
Using only vw in the preferred value. Pure
vwtext ignores the user's browser zoom and font-size settings. Always add aremcomponent so zoom still has an effect. -
Min larger than max.
clamp(3rem, 2vw, 1rem)silently resolves to the minimum. - Mixing px and rem endpoints. Pick one unit so the numbers stay predictable. rem respects user preferences.
- Forgetting line-height. A fluid font size with a fixed pixel line-height creates cramped or overlapping text at some sizes. Use a unitless line-height such as 1.5 so it scales with the font.
Try it
Try it: CSS clamp() Calculator
It runs entirely in your browser, so nothing is uploaded. There are 590+ other developer tools at webdevtoolbox.com too, such as a type scale generator and a px/rem/em converter.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.