Advanced HTML Tables

Basic HTML tables are fine for most applications where information fits neatly into a set number of rows and columns. But there are times when we might want a bit more control over the table, so that we can set up a more unorthodox structure where cells can be merged together.

Thankfully HTML offers us a very simple way to join two or more cells together - the colspan and rowspan attributes. By using the colspan or rowspan attributes, along with a number to tell the table how many rows or columns to span, we can join cells together with ease.

Colspan

colspan is probably the most commonly used of the span table attributes. Take a look at the following example to see how we can join two or more rows together:

NOTE: In this example you will see I have used the border table attribute. This is just a quick fix to help you visualize the table layout, it should not be used in practice; instead use CSS to style your tables.

<table border="1">

<tr>
<td colspan="2">2 column span</td>
<td colspan="3">3 column span</td>
</tr>

<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 5</td>
</tr>

</table>

This code will display a table like this:

2 column span 3 column span
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5

As you can see, by using the colspan attribute we have merged cells in the top row together, perfect for large headings that apply to more than one column.

Rowspan

rowspan works in exactly the same way as colspan, only it merges rows rather than columns. We can see it in action here. Again I have used the border attribute to make the layout more clear, but this is bad practice so avoid it at all costs:

<table border="1">

<tr>
<td rowspan="2">Spanned rows</td>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>

<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>

</table>

Which will produce the following layout:

Spanned rows Cell 1 Cell 2
Cell 3 Cell 4

You should notice one important thing here - take a look at the code for the second row, the one that contains Cells 3 and 4. You will see that we haven't had to add a <td> for the first cell in the row because it is merged with the one above. As such, its properties are controlled entirely by the <td> in the first row, the one that contains the rowspan attribute.

Combining colspan and rowspan

colspan and rowspan can be used simultaneously in the same table to produce a complex table layout. This can be quite a confusing process, but in the next lesson we will look at a technique to make sure you nail your tables first time, every time.