When designing a CSS grid system, the first thing you should bear in mind is not CSS but accessibility. I see many CSS frameworks that go beyond an acceptable number of columns and end up with featuring a grid with more than ten columns! Remember that some categories of users may experience several difficulties if you overuse the possibilities offered by CSS. Using a grid with a maximum number of four columns is quite accessible, though low-vision people may report some problems even with this choice. In this article we'll see a basic implementation of a responsive CSS grid system.
The markup
Our markup will resemble the structure of an HTML table, showing rows and columns:
<div id="container"> <div class="row"> <div class="box full"> </div> </div> <div class="row"> <div class="box half"> </div> <div class="box half"> </div> </div> <div class="row"> <div class="box third"> </div> <div class="box third"> </div> <div class="box third"> </div> </div> <div class="row"> <div class="box fourth"> </div> <div class="box fourth"> </div> <div class="box fourth"> </div> <div class="box fourth"> </div> </div> </div>
The CSS
Here's the meaning of the four CSS classes used above:
Class | Meaning |
---|---|
full |
One column |
half |
Two columns |
third |
Three columns |
fourth |
Four columns |
And here's the CSS code:
#container { width: 90%; margin: 1em auto; font-size: 76%; } div.row { background: #eee; overflow: hidden; margin-bottom: 1em; } div.box { float: left; } .full { width: 100%; } .half { width: 50%; } .third { width: 33%; } .fourth { width: 25%; }
As you can see, this is only a basic implementation of a grid. For example, you need to add some spacing between columns. To do this, you have to recalculate the overall width of each containing block by summing up margins or padding to the total.
You can see the demo below.