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})
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.