HTML Tables and Colspan

Webster defines a column as: a vertical division of typed or printed lines on paper.

In Figure #1 shown below we have divided a rectangle into 9 equal columns and colored them red and white.


Figure #1

The code:
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>

 

colspan is an attribute of the <td> tag. It tells the browser how many columns one cell of a row should span. It is used with multi row tables divided into multiple columns.

In Figure #2 shown below we illustrate the concept with a green row that spans 7 columns and a blue row that spans 5 columns.

diagram
Figure #2

Simplified code green:
<tr><td colspan="7"></td><td></td><td></td></tr>
Simplified code blue:
<tr><td colspan="5"></td><td></td><td></td><td></td><td></td></tr>

Text Example

Though you should not use colspan to control text and a simple image on a page, like the example below, colspan comes in handy when you have to present complicated data presentations.

We added a border here because it will make the concept of colspan easier to see.

Sometimes you want a cell to reach across two or more columns. If you don't

use colspan, the browser tries to keep things symetrical. That may not be the right word, but when we add colspan you'll see the difference.

dog

This is what it looks like without.

Without colspan


Sometimes you want a cell to reach across two or more columns. If you don't

use colspan, the browser tries to keep things symetrical. That may not be the right word, but when we add colspan you'll see the difference.

dog

This is what it looks like with.

With colspan

Here's the code using colspan. We left out paragraph tags to make it clearer.

<table width="300" border="1">
<tr>
<td colspan="2">text</td>
</tr>
<tr>
<td>text</td>
<td><img src="images/doggy.gif" alt="dog"></td>
</tr>
<tr>
<td colspan="2">text</td>
</tr></table>

In the example above we have a 3 row table.
The second row has 2 columns.
The first row has one cell that spans 2 columns.
The third row has one cell that spans 2 columns.