Today, I was faced with a problem I try to avoid at all costs: a 3-column layout of a list of items (not a full-page layout). This is the sort of thing where people usually say “stick it in a table and be done with it,” but that seemed like a cop-out to me, so I decided I’d make it work with CSS.
<ul>
<li>Ford</li>
<li>Mercury</li>
<li>Jaguar</li>
<li>Chevrolet</li>
<li>GMC</li>
<li>Lincoln</li>
<li>Toyota</li>
<li>Lexus</li>
<li>Scion</li>
</ul>
ul
{
padding: 0px;
}
ul li
{
display: block;
width: 33.3%;
float: left;
}
The magic here is the width on the list elements, combined with the float. If we force the width to 100/n (where n is the number of columns per row), the float will force the n+1th li down to the next row. Since every li has the same width, you always get the same number of elements per row. Since the actual markup is just an unordered list, you get the benefits of semantics while retaining the clean, table-like look.
You can adjust the display to have more or less items per row by tweaking the width. For example, to have five columns per row, you’d just need to set the width to 20%. If you were using a table, you’d have to fiddle with your markup to accomplish this.
It’s also better than using the display: table-cell CSS construct, since you have to encapsulate the data into more elements (with display: table-row set) to make that work. table-cell/row is also not supported on IE. This technique, on the other hand, works perfectly in IE, Firefox, Konqueror, and Safari.