Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Using the CSS calc() function

The calc() is a CSS function that lets you calculate values right in your CSS. For example:

.main-content {
  width: calc(100% - 40px);
}

One of the most useful features of this function is that you can mix multiple CSS units. In our example, we used a percentage with pixels. Bun we can also use units like em, pt, rem, etc.

In 90% of the cases, I find myself using calc with the substractions sign, but you can use it along with:

  • additions by using +
  • subtractions by using -
  • multiplication by using *
  • division using by /

The operator must be wrapped in white spaces. Some operators don't work well if you don't have a white a before and after it.

// use this code 
.logo {
  height: calc(4rem - 30px);
}
// instead of this one
.logo {
  height: calc(4rem-30px);
}

It is supported in all major browsers https://caniuse.com/#feat=calc.

Using calc() with CSS variables and SASS

It works out of the box with the new CSS variables:

--text-input-width: 500px;
max-width: calc(var(--text-input-width) / 2);

Using calc() in SASS or SCSS

For SASS variables you will have to interpolate the value in the calc() function:

$body_padding}: 20px;
 height: calc(100% - #{$body_padding})
Home Screencasts Best of Newsletter Search X