CSS Functions: calc, min, max & clamp
CSS can do maths. calc() combines different units, and min(), max() and clamp() choose between values — which makes fluid, responsive sizing possible in a single line, often without any media queries.
calc()
calc() can add, subtract, multiply and divide, mixing units freely — percentages with pixels, rems with viewport units. Spaces around + and - are required: calc(100% - 20px), not calc(100%-20px).
calc() with variables
Multiplying a base variable builds a consistent spacing scale.
min() and max()
min(a, b)uses the smaller value — handy as a maximum: "100%, but at most 400px".max(a, b)uses the larger value — handy as a minimum: "3vw, but at least 1rem".
The naming feels backwards at first: min() sets an upper limit, max() a lower one.
clamp(): fluid with limits
clamp(min, preferred, max) uses the preferred value but keeps it within the limits. For font sizes, mix a rem part into the preferred value (1rem + 2.5vw) so the text still responds to users' zoom and font-size settings — pure vw text can't be zoomed.
A fluid type scale
A set of clamped sizes like this replaces several breakpoints of font-size overrides.
Other functions
| Function | Use |
|---|---|
var() | Read a custom property (lesson 13) |
attr() | Read an HTML attribute (in content) |
round(), mod(), rem() | Round values to a step; remainders |
abs(), sign() | Absolute value and sign |
sin(), cos(), tan(), pow(), sqrt() | Trigonometry and powers — circular layouts, easing |
color-mix(), oklch(from …) | Colour maths (lesson 10) |
env() | Environment values, like the safe area around a phone's notch |
url(), image-set() | Images |
repeat(), minmax(), fit-content() | Grid tracks (lesson 29) |