Guide
How to use CSS clamp()
One line of CSS that scales spacing and type smoothly between two screen sizes. No breakpoints, no jumps.
What clamp() does
clamp() takes three values and returns the middle one, as long as it stays between the other two:
clamp(minimum, preferred, maximum)- Minimum: the smallest the value is ever allowed to be.
- Preferred: the value you actually want. It usually contains a viewport unit like
vw, so it grows with the screen. - Maximum: the largest the value is ever allowed to be.
Reading a clamp
Take the value this tool generates by default:
padding: clamp(1rem, -0.75rem + 7.292vw, 8rem);On a narrow phone the preferred value is smaller than 1rem, so the padding holds at 1rem. As the screen gets wider, 7.292vw grows and the padding grows with it, in a straight line. At a viewport of 120rem (1920px) it reaches 8rem and stops there.
You rarely write that middle part by hand. Pick the smallest and largest value, pick the screen sizes where they should apply, and let the generator do the maths. The deep dive explains where the numbers come from.
See the difference
Both screens below get 16px of padding on small screens and 64px on large ones. The first uses two media queries, the second a single clamp(). Drag the slider and watch the pink area.
The media query version jumps at 768px and 1024px and stays flat everywhere in between. The clamp version never jumps: every screen width gets its own padding.
Using the generator
- Choose Container to preview spacing, or Text to preview font sizes.
- Set the minimum and maximum value: the size on the smallest and the largest screen.
- Set the viewport range: the screen widths where the value should start and stop growing. Match these to your design, for example 24rem (384px) to 120rem (1920px).
- Drag the screen width slider to check the result, then copy the value.
When to reach for it
Clamp is at its best for values that should feel proportional to the screen:
- Page and section padding, and gaps between large blocks.
- Headings and display text.
- Gutters in grids and card layouts.
It is less useful when:
- The layout changes shape. Going from one column to three is a job for a media or container query, not a fluid value.
- The value is tiny. Scaling a 4px border radius to 6px is invisible and only makes the code harder to read.
- You need an exact value at an exact size. If a design specifies 24px at 768px and nothing in between, a breakpoint says that more clearly.
Tips
- Use
remfor the minimum and maximum, so the value still respects the user's font size setting. - Keep body text close to fixed. A fluid range like 1rem to 1.125rem is plenty; save the big ranges for headings.
- Put fluid values in variables or design tokens, so you only write each clamp once.
Further reading
- The deep dive: the maths, zoom and accessibility, and container units.
- clamp() on MDN
- CSS Values and Units, Level 4