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})

📖 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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X