In this tutorial, we’re going to learn about calc() in CSS.

The calc() function is used to perform simple calculations in CSS. We can work with addition (+), subtraction (-), multiplication (*), and division (/) operators.

The most useful feature of this function is the ability to mix units. For example, you could use it to subtract pixels from the viewport width:

.main {   
   height: calc(100vh - 80px); 
}

Using calc

The calc() function only works with values. So you’d only ever use it when expecting a pixel value.

Let’s take a look at some possible use cases..

We could use it to calculate the full viewport width, minus 200px accounting for a side nav:

div {
   max-width: calc(100vw - 200px);
}

Or to put a ‘scroll to top’ button at the bottom-right corner of a page:

body {
   background-image: url(arrow.png); 
   background-position: calc(100% - 25px) calc(100% - 25px);
}

Or when working with typography:

.text {
  font-size: calc(2vw + 5px);
  width:     calc(100% - 10px);
  height:    calc(100vh - 20px);
}

It can also be used as a part of shorthand properties:

margin: calc(6.25% - 5px) 0;

Unfortunately, it doesn’t work for media queries 😢:

@media (max-width: 30rem) {
  /* Works! */
}
@media (min-width: calc(30rem + 1px)) {
  /* Doesn't work */ 
}

The real power of calc()comes from the ability to mix units. And every example above has done just that! The ability to perform math operations when working with lengths, is a great reason to start using calc!

Related Posts:


Tim profile image

A little about me..

Hey, I’m Tim! 👋

I’m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! 🎉