CSS units · Arithmetic on mixed units
calc, min, max and clamp
These functions combine lengths and bound them without JavaScript.
Key facts
| calc | Arithmetic on mixed units |
|---|---|
| min/max | Choose the smallest or largest |
| clamp | <code>clamp(min, preferred, max)</code> |
| Nesting | Functions can contain each other |
| Evaluation | At computed-value time |
| Standard | CSS Values and Units Level 4 |
Arithmetic with units
calc() adds, subtracts, multiplies and divides lengths, provided the result is a valid length. It is how a sidebar can be calc(240px + 2rem) or a full-width element can subtract a gap: calc(100% - 2rem). Whitespace around + and - is required.
min() and max() choose a bound. They are useful for responsive sizes that should not exceed a pixel maximum, such as min(40vmin, 320px).
clamp for fluid type
clamp(min, preferred, max) returns the preferred value constrained between the bounds. A typical fluid heading is clamp(1.5rem, 4vw, 2.5rem), which grows with the viewport but never becomes too small or too large. If the minimum is greater than the maximum, the minimum wins.
These functions are evaluated by the browser, not by a preprocessor, and they work in custom properties. They cannot, however, make a percentage height work inside an auto-height parent; the underlying reference problem remains.
Frequently asked questions
Why does calc() fail with a minus sign?
Addition and subtraction require whitespace around the operator. calc(100%-2rem) is invalid.
Is clamp() supported everywhere?
In current browsers, yes. Provide a plain fallback declaration before it for older engines.