Using CSS calc() to create flexible, fluid grids

If you need to create a grid of elements that are evenly spaced, and at the same time align the outer borders of this grid with other elements, it is less obvious than it might appear.

If the container element has a fixed width, then it’s quite easy to do the math and specify absolute dimensions for all the elements.

On the other side, if the container has a variable width, or if we want to style a grid with a variable number of rows, then we need to find another solution.

In this case, using a simple table would not help, because while we can easily specify the cell spacing, the same cell spacing will be applied to the outer borders of the table, which would result smaller than its container.

A possible solution is to use CSS3’s calc() function – check here for the browser compatibility.

By combining it with some basic php code and CSS inline styling, it is possible to create a very flexible grid layout, with evenly spaced and equally sized grid cells :


$arr_data = array('item_1','item_2','item_3','item_4','item_5','item_6');

foreach($arr_data as $data_item) 
  echo'<div class="grid-item" style="float:left; ';
  echo 'width:calc((100% - '.($n_cols-1)*$cell_spacing.'px)/'.$n_cols.');';
    //last element in a row
    echo 'margin:0;';    
    echo 'margin-right:'.$cell_spacing.'px;';    
  echo '">';

  //Grid cell content
  echo $data_item;

  echo'</div>'; //closes div.grid-item

Leave a comment