1. Introduction

calc() is a native CSS function that allows us to perform mathematical operations when specifying property values. In other words, it gives us the ability to perform calculations with different units in our CSS code.

It supports the following arithmetic operations: addition (+), subtraction (-), multiplication (*), and division (/).

We can do calculations when defining number values for the CSS properties in our code. It's a useful feature since CSS is pretty heavy on length values and other numerical values.

<aside> ℹ️ MDN page for the CSS calc() function can be found on this link.

</aside>

CSS preprocessors (tools that add features to standard CSS) like Sass also have math functions, but the native calculations can be more powerful. Natively, we can directly mix different units like percentages and pixels in our calculations.

For example, we could make the width of an element 50% of the available area plus a fixed amount of space like 20px.

1.1. Browser support

The CSS calc() function has good support in modern browsers, as seen in the following chart (February 2020):

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1011a55b-128a-4594-9a01-4c7f66bc1f05/Untitled.png

You can find full browser support charts for the CSS calc() function on this page.

<aside> ℹ️ If a particular browser doesn't support the calc() function, it should ignore it. That means we can provide a fallback static value for browsers that don't support it.

</aside>

2. Syntax

We pass a single expression as the parameter to the calc() function:

div {
  /* property: calc(expression) */
  width: calc(80% - 100px);
}

The result of the expression that was passed to the calc() function is used as a value for the specified property.

In the example above, we are allocating 80% of the available area minus the fixed amount of pixels (100px) to the width of a div element. If the element is placed on the left, we know for certain that it will always have 100px of available space on the right side, while the 80% area will change depending on the size of its parent element.

As already mentioned, the expression that we pass to the function can combine the following operators: