DEV Community

Michael Kelly
Michael Kelly

Posted on

How CSS clamp() works (and a free generator that does the math for you)

The CSS clamp() function is one of the most useful tools in modern CSS,
but the math to get a correct preferred value is tedious to do by hand.

What clamp() actually does

clamp(minimum, preferred, maximum) locks a value between a floor and ceiling
while letting it scale proportionally between them based on viewport width.

For fluid typography, the preferred value is a linear interpolation between
two known points: the size you want at your smallest viewport, and the size
you want at your largest.

The math

Given:

  • minViewport = 320px
  • maxViewport = 1920px
  • minSize = 1rem (16px)
  • maxSize = 2.5rem (40px)

The formulas are:

slope = (maxSize - minSize) / (maxViewport - minViewport)
intercept = minSize - (slope x minViewport)
preferred = intercept + (slope x 100vw)

Which produces:

font-size: clamp(1rem, 0.7rem + 1.5vw, 2.5rem);

That single line replaces multiple media query breakpoints and eliminates
layout shift from abrupt size jumps.

Why rem instead of px

Using rem respects the user's browser font size preference. If someone has
increased their base font size for accessibility, rem values scale with it.
Pixel values are absolute and override user preferences entirely. For font-size
specifically, rem is the accessible choice.

The generator

I built a free tool that handles the calculation and outputs a ready-to-paste
CSS declaration:

https://clampgen.com

It supports any CSS property (not just font-size), has a rem/px toggle,
quick presets for common type scale targets, and a breakdown panel that
shows you the slope and intercept values so you can verify the math yourself.

Built with vanilla HTML/CSS/JS and hosted on Netlify. No login, no email
capture, just the tool.

Top comments (0)