Skip to main content

CSS Math Functions

Property values in CSS can be mathematical expressions, thanks to math functions.

This chapter looks at four of them:

  • calc()
  • max()
  • min()
  • clamp()

The CSS calc() Function

Use calc() when a property value has to be the result of a calculation.

The supported operators are addition (+), subtraction (-), multiplication (*), and division (/), and units can be mixed, for example pixels with percentages.

Example

Both the width and the height of this <div> element come from calc().

Prompt
Create a page with a div that uses calc() to set its width to 100% minus 100px and its height to 30vh plus 50px. Center it with margin auto and add a 1px solid black border and 10px padding.
Output: complete HTML page

CSS Syntax

styles.css
calc(expression)

The CSS max() Function

Given a comma-separated list, max() picks the largest value and uses it for the property.

Example

Between 50% and 300px, max() gives the width of #div1 whichever is larger.

Prompt
Create a page with a div that uses max() to set its width to whichever is largest: 50% or 300px. Give it a height of 100px, a 1px solid black border, and 10px padding.
Output: complete HTML page

CSS Syntax

styles.css
max(value1, value2, ...)

The CSS min() Function

Given a comma-separated list, min() picks the smallest value and uses it for the property.

Example

Between 50% and 300px, min() gives the width of #div1 whichever is smaller.

Prompt
Create a page with a div that uses min() to set its width to whichever is smallest: 50% or 300px. Give it a height of 100px, a 1px solid black border, and 10px padding.
Output: complete HTML page

CSS Syntax

styles.css
min(value1, value2, ...)

The CSS clamp() Function

A value that responds to the viewport size but stays within limits comes from clamp(): it moves between a minimum, a preferred value, and a maximum.

Those three are also its parameters, and they resolve like this:

  • A preferred value between the min and max is used as it is.
  • A preferred value below the min gives way to the min value.
  • A preferred value above the max gives way to the max value.

Example

The <h2> element's font-size is 5vw, limited to at least 1.5rem and at most 3rem. The <div> element also relies on clamp(), for both its font-size and its width.

Prompt
Create a page with an h2 using clamp() for font-size (min 1.5rem, preferred 5vw, max 3rem) and a div with clamp() for both font-size (min 1rem, preferred 2.5vw, max 2rem) and width (min 200px, preferred 50%, max 600px). Add a 1px solid green border and 10px padding to the div.
Output: complete HTML page

CSS Syntax

styles.css
clamp(min, preferred, max)