Demo can be found here.

Calc() is a native CSS function that allows you to use mathematical expressions with addition, subtraction, multiplication and division. The basic syntax works like this:

.article { float: left; width: calc(100% - 1em); }

You can use any length values you want in the function, like em’s, pixels and percentages.

The grid

So, lets use calc() to create a really easy-to-use grid system.

The HTML

I myself am a fan of semantic grids and don’t want to use column class names in my HTML, so our the structure looks like this:

<header> <h1>CSS grid with calc()</h1> </header> <main> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pretium dui ut massa pretium quis ornare dolor elementum. </p> </main> <aside> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pretium dui ut massa pretium quis ornare dolor elementum. </p> </aside>

The CSS

A grid basically consists of two things:

Columns (most often 12 or 16 based)

Gutter

So what we need to create is something like this:

//Without gutter width: calc(100% / total_number_of_columns * columns ) //With gutter width: calc((100% / total_number_of_columns * columns) - the gutter)

It’s not as complicated as it might seem, though it took me embarrasingly long time to figure it out, because math is hard yo.

We divide the total amount of columns with 100% to get how wide each column should be, and then multiply that number with how many columns we want it to fill up.

So, lets write a function that takes columns and gutter as parameters, and returns the width.

$columns: 12; $gutter: 5%; @function grid-width($cols, $has-gutter:false) { @if $has-gutter { @return calc(((100% / #{$columns}) * #{$cols}) - #{$gutter}); } @else { @return calc((100% / #{$columns}) * #{$cols}); } }

We set the $has-gutter parameter as false by default, just for making the call to the function more convenient. Also, we need to interpolate our Sass variables to be able to use them in calc().

All we have to do now is call the function!

header { width: grid-width(12); } main { width: grid-width(8, true); background: tomato; float: left; } aside { width: grid-width(4); float: right; background: teal; }

This will create a 12 column based grid system, where main takes up 8 columns, and aside takes up 4.

Here’s the live demo:

See the Pen Grid with CSS calc() by sebastianekstrom (@sebastianekstrom) on CodePen.