Flexible grid system using calc()

, by

Almost one year ago, I wrote about how to make “A basic 16-lines-of-code CSS fluid grid” using inline-block instead of the usual float. Today I’ll show you how to build a grid system using the calc() property.

What is the calc() property ?

Introduced in 2011, the calc() property allows us to calculate directly in CSS any length, number, angle, etc. It also lets us mix measurement types like %, em, px. It receives the four math operators:

  • add (+)
  • subtract (-)
  • multiply (*)
  • divide (/)

For instance :

.myClass { width: calc(300px - 2em); }
/* output: 268px = 300px - 2x16 */
.myClass { width: calc(30em / 2); }
/* output: 240px = 30x16 / 2 */
.myClass { width: calc(50% + 2em); }
/* if body=940px, output : 502px = 940x50% + 2x16 */

Building columns using pixels

Let say we would like :

  • a 960px large layout
  • with 10px padding each side (left & right)
  • 3 identical columns (300px)
  • and 2 gutters ( (960 - 10x2 - (300 x 3) ) / 2 = 20px per gutter)

Considering the following HTML :

<div class="gs">
    <div class="g"> Column n°1 </div>
    <div class="g"> Column n°2 </div>
    <div class="g"> Column n°3 </div>
</div>

… we would write this CSS :

body {
    width: 940px;
    margin: 0 auto;
    padding: 10px;
 }

.gs { overflow: hidden; }

.g {
    float: left;
    width: 300px;
    margin-right: 20px;
}

.g:last-child { margin-right: 0; }

Building flexible columns using percentage (%)

body {
    max-width: 940px;
    margin: 0 auto;
    padding: 10px;
 }

.gs { overflow: hidden; }

.g {
    float: left;
    width: 31.9149%; /*300px*/
    margin-right: 2.1276%; /*20px*/
}

.g:last-child { margin-right: 0; }

Building flexible columns using calc()

body {
    max-width: 940px;
    margin: 0 auto;
    padding: 10px;
 }

.gs { overflow: hidden; }

.g {
    float: left;
    width: calc(300/940*100%); /*300px*/
    margin-right: calc(20/940*100%); /*20px*/
}

.g:last-child { margin-right: 0; }

Lines are a bit longer but now you don’t need to calculate percentage with decimals.

In the following line width: calc(300/940*100%) :

  • “300” is the width of the column
  • “/940*100%” is how I calculate the percentage
  • I wrote “300” instead of “300px” in order to get a result in percentage.

I like to use this method, specially if I don’t use SASS.

Browser support

https://caniuse.com/#feat=calc