clamp() takes three values: minimum, preferred, maximum.
font-size: clamp(1.5rem, 4vw, 3rem);
- Usually uses
4vw(the preferred value, which changes with the screen). - But never goes below
1.5rem. - And never goes above
3rem.
<style>
h1 { font-size: clamp(1.5rem, 5vw, 3.2rem); margin: 0 0 8px; line-height: 1.15; }
.box { padding: clamp(0.75rem, 3vw, 2rem); background: #fdf2e9; border-left: 6px solid #d94a00; }
</style>
<div class="box"><h1>Fluid heading</h1><p>The padding is fluid too.</p></div>
It is shorthand for max(min-value, min(preferred, max-value)), which would be awkward to write by hand.
The “preferred” value must scale
If the middle value is a fixed length, clamp does nothing interesting. It must contain something that changes: vw, %, or rem + vw.
A useful pattern is to add a rem part to a vw part:
font-size: clamp(1rem, 0.9rem + 0.5vw, 1.25rem);
The rem in the middle keeps the text responding to the visitor’s own font settings. Pure vw text ignores them, and that is an accessibility problem. See Responsive Typography.
What else can it do?
Anything that takes a length:
.container { width: clamp(20rem, 90%, 70rem); }
.section { padding-block: clamp(2rem, 6vw, 5rem); }
.gap { gap: clamp(8px, 2vw, 24px); }
How to choose the numbers
- Decide the smallest and largest size you want.
- Set the middle so it passes through them at the screen widths you care about. Online “fluid type” calculators produce this. You do not need to calculate by hand.
Exercise: a fluid section padding
Give a section vertical padding that is never less than 2rem, never more than 6rem, and is 8vw in between.
Show a possible solution
section { padding-block: clamp(2rem, 8vw, 6rem); }