DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on Edited on

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 getting it wrong breaks zoom and accessibility.

The syntax

h1 {
  font-size: clamp(1.5rem, 1rem + 2.5vw, 3rem);
}
Enter fullscreen mode Exit fullscreen mode
  • 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.

  1. Slope = (32 - 16) / (1280 - 320) = 0.016667, which is 1.6667vw.
  2. Intercept = 16 - 0.016667 x 320 = 10.667px = 0.6667rem.
  3. Result: clamp(1rem, 0.6667rem + 1.6667vw, 2rem).

Mistakes that bite

  1. Using only vw in the preferred value. Pure vw text ignores the user's browser zoom and font-size settings. Always add a rem component so zoom still has an effect.
  2. Min larger than max. clamp(3rem, 2vw, 1rem) silently resolves to the minimum.
  3. Mixing px and rem endpoints. Pick one unit so the numbers stay predictable. rem respects user preferences.
  4. 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.

Top comments (0)