CSS: fluid grid systems

I'm currently testing some of the recent and new possibilities offered by CSS grids and I have to say that I still haven't found what I'm looking for. Most of these grids are based on fixed sizes, meaning that the current base grid is made up of lengths measured in pixels. Pixels are a bad approach to CSS design because this approach actually doesn't take into account the problem of screen resolution. In fact, a 960 pixels grid system fails spectacularly on the most recent versions of PC and Mac monitors: simply put, it doesn't fill well the screen. A better approach is to use percentages. Let's see how.

How percentages work

Percentages in CSS are calculated by taking the width and height of the parent element as a reference. The base value is always 100%. For example, if you want to have five boxes on the same line, you could write something like this:

#container {
 width: 100%; 
}

div.box {
 display: inline-block;
 width: 20%;
}

20 multiplied by 5 gives 100, so you have five boxes that fill completely the width of their parent element. On the other hand, heights work better when they're previously defined on the parent element:

#container {
 width: 100%;
 height: 200px; 
}

div.box {
 display: inline-block;
 width: 20%;
 height: 90%;
}

In this case, 90% must be calculated by taking 200 pixels as its reference.

Using minimum and maximum lengths

CSS provides four powerful properties that can be combined with percentages, namely:

  1. min-width
  2. max-width
  3. min-height
  4. max-height

You can use these properties to keep your layout proportions when the screen resolution is too high or too low. Example:

#site {
 width: 90%;
 margin: 0 auto;
 max-width: 1000px;
 min-width: 700px;
}

This technique is widely used by some of the newest WordPress themes, including TwentyEleven. It simply tells browsers that the overall width of the main container should not exceed 1000 pixels and should not be less than 700 pixels. Try to resize the browser's window to see the effect.

Rounding problems

Suppose that you have a container with three floated boxes inside. You want to equally redistribute the horizontal space so that all the boxes fit their container's width:

#container {
 width: 100%;
 overflow: hidden;
}

div.box {
 float: left;
 width: 33.3%;
}

33.3 multiplied by 3 gives 99.9, but you can use more decimal points if you want. The problem with all this rounding is that some versions of Internet Explorer (namely 6 and 7) tend to round up your values. The final result in these browsers is rather ugly: floated boxes are pushed on the next line. To fix this, always remember to round down your values for IE 6 and 7.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.