February 12th, 2008

Using the DIV tag to display columns rather than tables

A common mistake that people make when developing web sites for accessibility is to use the <TABLE> element to control their layouts. The <TABLE> element is convenient, easy to work with and produces layouts that are stable across different browsers. However, the W3C WAI guidelines are pretty clear on this: tables are for displaying tabular information, not for arranging page content.

A solution

Consider the column example below:

Column 1
Column 2
Column 3

These columns are created by wrapping three <DIV> tags within one containing <DIV>. The container <DIV> tag has its width set to 450 pixels and the width of each column is set to 150px. In order to make the columns line up, you need to set the float style for each of the contained <DIV> tags to left.

The code examples below show how this is done using a set of styles defined in this page’s stylesheet. The containing <DIV> element is formatted by the “example” style, while each column is controlled by one of the three styles “example_column1″, “example_column2″ and “example_column3″.

Here’s the HTML:

<div class="example1">
    <div class=”example_column1">Column 1</div>
    <div class="example_column2">Column 2</div>
    <div class="example_column3">Column 3</div>
</div>

Here’s the CSS styles:

div.example1
{
width: 600px;
color: #ffffff;
}
div.example1 div
{
float: left;
width: 200px;
height: 100px;
}
div.example1 div.example_column1
{
background-color: #121212;
}
div.example1 div.example_column2
{
background-color: #454545;
}
div.example1 div.example_column3
{
background-color: #787878;
}

When calculating the columns size, take into account any padding and the width of any borders as both are added to the width of the column. For example, a column that is 150px wide with padding of 5px and a border of 1px should be set to 144px wide.

Limitations with proportional layouts

This technique is great for fixed-width layouts, but less effective for proportional layouts where a mixture of fixed-width and proportional layouts are required. I’ve always assumed that this limitation does help to explain the scarcity of proportional layouts on the web. When it comes down to it, HTML and CSS do tend to favour carefully planned fixed layouts.