Wednesday, 20 June 2007

CSS Layout - Columns, Headers and Footers

Most websites these days seem to have a standard layout. There is a header at the top, a footer at the bottom, and then one or two thin bars of links or adverts down either side. Using tables, this is relatively simple to do - it's a table with three rows and three columns:

<table border="1">
<tr>
    <td colspan="3"><b>Header</b></td>
</tr>
<tr>
    <td width="20%">Left Column</td>
    <td width="60%">Centre Column</td>
    <td width="20%">Right Column</td>
</tr>
<tr>
    <td colspan="3"><i>Footer</i></td>
</tr>
</table>
    <td colspan="3">Footer</td>
</tr>
</table>

But this is seriously out of fashion these days. You are now expected to use CSS, which can be a bit frustrating to learn at first. Here's how to generate a three column layout in CSS, which will expand in width to use your whole browser window.

The first thing to do is ditch the table and use div tags:

<div id="header">Header</div>
<div id="left-col">left column</div>
<div id="right-col">right column<br/>link</div>
<div id="centre-col">centre column</div>
<div id="clear"></div>
<div id="footer">footer</div>

This is all fairly straight-forward, except the need for the clear div, which ensures the footer stays at the bottom of the page.

Now we need to write the styles. For the most part, they are simple to understand.

#header {
border:solid thin gray;
text-align:center;
font-size:x-large;
font-weight:bold;
margin:5px;
}

#left-col {
border:solid thin gray;
margin:5px;
width=150px;
float:left;
}

#right-col {
border:solid thin gray;
margin:5px;
width=150px;
float:right;
}

#centre-col {
border:solid thin gray;
margin:10px 160px 5px 160px;
min-height:400px;
}

#footer {
text-align=center;
border-top:dashed thin gray;
margin:5px;
font-style:italic;
}

#clear {
clear:both;
}

Points of interest:

  • The centre column has to provide left and right margins wide enough not to obscure the left and right columns.
  • The min-height property ought to ensure that the page does not appear artificially squashed if there is no content. However, I am not sure this is working in all instances.
  • Borders and margins can be used together to create a much nicer looking separation of sections than can be achieved simply with tables.
  • You have to put the right column before the centre column for layout to work correctly.

 

Post a Comment