Calculations In CSS With calc()

November 30, 2018 by Andreas Wik

calc() is a nifty little feature in CSS which lets you – oh yeah, you guessed it – calculate stuff. Great when working with values that need to be dynamic and that you otherwise would have to achieve with JavaScript.

So let’s take a look at an example where this could be handy. Imagine if you wanted to place a background image a certain distance from the bottom right corner.

Placing a background image a certain distance from the top left corner is easy:

See the Pen Background image 15px from top left corner by Andreas Wik (@andreaswik) on CodePen.

 

But what if we want it 15px from the bottom right corner? This is a great example where we could use calc(). Take a 100% of width and subtract as much as you want, in this case 15px:

See the Pen calc() background image position bottom right by Andreas Wik (@andreaswik) on CodePen.

 

I’m sure you can think of way more situations where this could be useful. I ran into this article https://vincentp.me/blog/use-cases-for-calc by Vincent Pickering which goes through a bunch of examples.

Share this article

Recommended articles