Flexible grid system using calc()
, by Aurélien Aries
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
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 :
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 :
… we would write this CSS :
Building flexible columns using percentage (%)
Building flexible columns using calc()
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.