Min Tran

Design. Rock and Roll.

Responsive grid using calc

In the age of responsive design, design components should be as flexible as possible. My ideal grid is the one with fluid column width and a fixed margin between column because so we can adapt it to any viewports easily, while keeping the gutter and space consistent.

In the past year I relied on a technique called "text-align: justify grid", which uses the good old text-align:justify to adjust the column width automatically and the margin stays intact. This approach works I feel guilty to see many placeholderrs DIVs in my HTML. It's 2015, not 2005!

I was searching for a way to create fluid grid with fixed column margin following this formula:

Column width = 100% / number of columns - margin between columns

Unfortunately, there was no way to do this kind of mixed unit calculation; until later I discovered a little gem called calc. Calc is the first and only CSS function which allows us to deal with math. The most beautiful thing about calc is it works with just any units. It helps bring my idea to life:

As you can see, the CSS is very straightforward and calc does all the magic:

width: calc(100% / $column-desktop - $margin);

We should use display:block and the infamous float:left instead of display:inline-block to get rid of the extra space inline-block generates. I use Sass for variables and media queries for the sake of convenience but you can achieve the same result with native CSS.

Calc is an approved and supported CSS function, its performance is superb. As you might guess, this technique only works in modern browsers that support calc. This is my go-to method for grid building, while we're waiting for flexbox's maturity.

comments powered by Disqus