My blog has moved!

You should be automatically redirected. If not, visit
http://benohead.com
and update your bookmarks.

Tuesday, November 8, 2011

Three column layout

The first possibility (and oldest one) is to simply use HTML tables to create the three columns. Basically, you create a table which only has one row and 3 columns.


<table width="100%">
    <tr>
        <td width="20%" style="vertical-align: top;">  
        …
        </td>
        <td width="50%" style="vertical-align: top;">
        …
        </td>
        <td width="30%" style="vertical-align: top;">
        …
        </td>
    </tr>
</table>
Pros: 

  • wide browser support

Cons: 

  • polluting the HTML with non-semantic tags
  • the content is not displayed the same when in a div tag or in a table cell

In order not to pollute our content with non-semantic tags (<table>,<tr> and <td>), the obvious solution is to switch to CSS tables. This allows to use semantically meaningful div tags by only having the formatting tables in CSS.


Here the HTML code:
<div id="leftcol">

</div>
<div id="middlecol">

</div>
<div id="rightcol">

</div>
And the CSS:
body {
    display: table; width: 100%
}
 
#leftcol, #middlecol, #rightcol {
    display: table-cell;
}
 
#leftcol {
    width: 20%;
}
 
#middlecol {
    width: 50%;
}
 
#rightcol {
    width: 30%;
}
Pros:
  • not polluting the HTML with non-semantic tags



Cons:
  • doesn't work in IE7 and earlier
  • using CSS tables does affect the rendering of the contents
The third possibility is to use CSS floats. Here we basically define a central column with a margin as wide as the left column and then have the left and right columns respectively float on the left and right side of the central column.

Here's the HTML:
<div id="middlecol">

</div>
<div id="leftcol">
...
</div>
<div id="rightcol">

</div>

It's important to first define the div for the middle column. From a semantic point of view, we could consider it being actually better since it's usually the main content column and the other 2 usually contain the navigation and sidebar.

Here's the CSS:

#middlecol
{
    float: left;
    width: 50%;
    margin-left: 20%;
}
#leftcol
{
    float: left;
    width: 20%;
    margin-left: -70%;
}
#rightcol
{
    float: left;
    width: 30%;
}
Pros:
  • not polluting the HTML with non-semantic tags
  • doesn't impact the rendering of the columns (except their positions)

Cons:
  • doesn't work in older browser


No comments:

Post a Comment