A basic 16-lines-of-code CSS fluid grid
I have to code a basic 4-column website project. I want something fluid and really simple where I can choose between a 1-column, 2-column, 3-column and 4-colum width.
I checked Bootstrap. The grid part of the CSS, which I often use for bigger websites, has 210 lines. It is a little bit too much for my project.
I checked 960.gs and adatp.960.js. It’s great but it has too many options for my needs.
I check several more … then I realize that I’ve been spending more time looking for it than coding it.
floats or inline-block ?
Each column of my design will have grey boxes inside with different heights. As Steven Bradley explained last year, using floats between elements of different heights can be problematic. Check this out : https://www.vanseodesign.com/blog/demo/inline-block/
Floats don’t go back to lines. I will use inline-block instead.
But inline-block brings another problem : it creates a little white space between each block. A quick way to fix this is to set up the font-size of the parent element to 0px.
Let’s get started. I will give the parent the class .gs
(for Grid System), and each column the class .g
.
I want a 4-column grid, so each column will have a 23% width and a 2% margin-right.
This is how it looks : https://jsfiddle.net/aastudio/XeQzU/1/
Deal with margins
As expected, there’s a margin on the right. To fix this I have several solutions :
First solution
Use the pseudo-class last-child .g:last-child { margin-right: 0; }
and change the width of the div to 23.6% .g { width: 23.6%; ... }
Problem :
last-child
is not IE8 compatible- 23.6% is not really understandable in the code : (23.5%x4) + (2%x3) = 100%
Second solution
Use the pseudo-class first-child
and a margin-left
instead
.g:first-child { margin-left: 0; }
. It is compatible with IE8 (even with IE7). But here is what happens : https://jsfiddle.net/aastudio/XeQzU/4/
The fifth box has a margin-left.
Third solution
Add a negative margin on the parent. The good thing with this solution is that we can keep the 23% on the boxes.
https://jsfiddle.net/aastudio/XeQzU/5/
4 different sizes
I already have the first-one. I need to add a 2-column size, a 3-column size and a 4-column size. I update my code this way :
My html would look like this :
The 16-lines CSS grid
Here is my final CSS :
Simple and short code !