HTML Dog

Skip to navigation

Tables: rowspan and colspan

Tables may have seemed complicated enough in the HTML Beginner Tutorial. It can be quite difficult to visualize a two-dimensional grid from one-dimensional lines of code.

Well, it gets trickier. All thanks to the rowspan and colspan attributes. Those bastards.

The following code is similar to that in the Tables page of the HTML Beginner Tutorial:


<table>
    <tr>
        <th>Column 1 heading</th>
        <th>Column 2 heading</th>
        <th>Column 3 heading</th>
    </tr>
    <tr>
        <td>Row 2, cell 1</td>
        <td colspan="2">Row 2, cell 2, also spanning Row 2, cell 3</td>
    </tr>
    <tr>
        <td rowspan="2">Row 3, cell 1, also spanning Row 4, cell 1</td>
        <td>Row 3, cell 2</td>
        <td>Row 3, cell 3</td>
    </tr>
    <tr>
        <td>Row 4, cell 2</td>
        <td>Row 4, cell 3</td>
    </tr>
</table>

Header cells

The first difference is that the td tags of the first row have been replaced with th tags. Whereas a td is a standard data cell, th is a header cell. As with td elements, these must be enclosed inside tr elements.

Spanning columns and rows

colspan and rowspan attributes have also been used in some of the td tags. If you look at this code in a browser, you will see that on the second row there are now two cells instead of three, the second cell spanning the second and third column. The colspan attribute, which means “column span” will span the cell over the number of cells that is specified. This means, in this example, that there is no need for a third td element - two cells are merged into one.

The rowspan attribute is similar to colspan, except, obviously, it will span across rows rather than columns. Again, the cells that it spans should be removed. In this example, because it spans over the fourth row, there are only two cells in that row.

As with the simpler 3x4, 12-cell table, the numbers on these tables with merged cells should also add up. Although there are only 10 cells in this example, there are 2 spans.