Kevin LeClair

Why Do Math When You Have Calc()

We’ve all been there. Floating divs left or displaying inline block with a set width can be a pain. It’s great if you don’t need a space between each element, but what if you want a little margin for your layout? Border box may include padding and border into your declared width, but it doesn’t include margin.

 div {
 display: inline-block;
 width: 33.33%;
 margin-right: 1px;

I’m sure you’ve stared at a code block like the example above many times thinking “How the hell does 1px go into 100% of my browser?” From there you’re having to switch your margin values to percentages, and then calculating how much width is left in your browser space so you can assign it the div’s main width.

Now I don’t know about you but that’s a little annoying for a guy like myself who almost failed Grade 11 math. Enter the calc() property! Instead of figuring out all those pesky numbers for your div’s width just write in this syntax:

width: calc(33.33% — 1px) /*replace 1px with your desired amount!*/

Take a look at this CodePen to see it in action.

It’s use is also well supported in most browsers!

sorry IE8 users….
sorry IE8 users….

If you are developing for IE8 or 9 then you’re stuck with math unfortunately! Same goes for the majority of Android browsers.

So if you’re sick of figuring out width percentages and want to just keep coding take a look at using calc!

Posted on March, 12 2015 in General

Leave a Reply

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