Easy CSS Columns: to Float or not to Float?

Design & Development

Jarrod Medrano Mar 31 2011

This method is based upon Float-less Layout. But I have made it simpler to fit my needs. I also don’t like how they make their entire site a list, while it seems to make sense, I find that putting a whole bunch of stuff inside a list becomes annoying fast, just like using tables.

Since I started making websites, one of the most annoying things I’ve had to deal with is creating a three or more column layout that is cross-browser compatible, and easy to update and maintain. For some reason this seemingly simple task has frequently led to many hair-pulling moments and frustrated cries of ‘why don’t I just use a @#$# table?’ Of course, these problems will all be solved whenever css3 is supported by all the major browsers, but until then I am sticking to display:table-cell;

Why We Float

why-use-css-floats.jpg
For many, many years I’ve used the css property float to align things to the left or right of something else. I started doing this because using table cells for non-tabular data was and still is a taboo among people who like to use words like ‘semantic‘ or ‘emergence‘, or for that matter ‘tabular‘ in every day conversation. In fact, just using the word ‘table‘ is likely to bring a rain of smug imbued Starbucks cups down upon my head.

Why Floats Blow

CSS Floats Blow

Floats are stupid for a number of reasons. When objects with backgrounds are floated beside each other, they usually end up looking like this:

floats

Example of CSS columns with floats.

What we normally want is this:

CSS - No Floats

Example of CSS columns with table-cell.

In my example files, each of the columns is given the class ‘column’. If we remove the column class from one of these columns, you can see another common issue we have with floating. Unless you add a clear for the float, for example:

The content in the last column will wrap around the floated elements. This is not a problem in the example with table cells.

wrapping

Example of common wrapping problem.

Pros and Cons:

Here’s a list of pros and cons for using display: table-cell; instead of floats.

Pros:

  • When floating the columns, I had to add height:100% to everything from the column up in order to paint the background completely, eliminating all of the red color. This isn’t necessary with the table-cell method.
  • No unnecessary clear class.
  • Numerous float related bugs and other headaches are avoided.

Cons:

  • You have to add a conditional comment for ie7 and less.
  • The background ‘painting’ problem isn’t so easily solved in ie7 and below.
  • It’s not so easy to add a margin to table cells.

In Summation

Use CSS floats if you’re doing something simple like floating an image and want text to wrap around it. Use CSS table cells if you want to do columns. Only use actual HTML tables if you are doing a table, like an excel document in your web page.