Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Functions

The calc() function

Reference for the CSS calc() function: mixing units, operator rules, nesting, custom properties and typed division, with live examples and usage notes.

The calc() function lets you do arithmetic where CSS expects a length, percentage, number, angle, time or other numeric value. Its power is that it mixes units at layout time: 100% - 40px is something no preprocessor can compute, because the percentage is only known once the page is laid out.

CSS
.sidebar {
  width: calc(100% - 20rem);
}

Try it

Mixing units

Syntax

CSS
calc( <expression> )

/* operators: + - * / */
width: calc(100% - 2 * var(--gap));

Syntax and arguments

Part Description
+ and - Need whitespace on both sides (10px+5px is invalid). Both operands must have compatible types, such as two lengths, or a length and a percentage where a percentage is allowed.
* At least one side must be a plain number.
/ The right side must be a number in classic CSS; newer browsers also allow dividing by a typed value. Avoid dividing by zero.
Parentheses Group sub-expressions; calc() can nest inside calc(), and plain parentheses work inside it.
Functions var(), min(), max(), clamp(), env() and attr() (where supported) can appear inside.
Keywords Math constants such as pi and e, and infinity, -infinity and NaN, are available in current browsers.

Usage notes

  • Whitespace around + and - is required, but not around * and /. This is the most common cause of a silently ignored declaration.
  • Percentages resolve against whatever the property normally uses. calc(50% + 10px) in width uses the containing block's width; in margin-left it also uses the containing block's width.
  • Unitless zero is not allowed in sums: calc(10px + 0) is invalid; write 0px.
  • Computing with custom properties: calc(var(--cols) * 100px) works when --cols holds a number. The value is substituted before parsing.
  • Result type must suit the property. calc(1px * 2) is a length; calc(1px / 1px) is a number in browsers that support typed division, which is still new, so check a compatibility table.
  • Readability: when a calculation repeats, store parts in custom properties.
  • Grid and flex: often fr units, gap or minmax() solve the layout without calc().
  • Performance: negligible. calc() is resolved during style and layout like any other length.

Browser support

Supported in every current browser. Newer features inside it (math constants, typed division) are more recent, so check a compatibility table for those.