Tables: Columns, Headers, and Footers
So you think you know how to make a table. Sure, you know the
th tags, you’ve even got the
colspan attributes in your pocket. You can make a really cute little plywood coffee table, but don’t you want to know how to make one of those polished solid wood, glass top dining tables that can take the weight of an oversized elephant?
You do? Oh joy.
The Columns Strike Back
Table rows tend to make table columns look rather stupid. They do all the work, as the table is built row by row, leaving the columns feeling quite rejected.
Luckily for those eager columns though, the
col tags have come to their rescue.
These tags allow you to define the table columns and style them as desired, which is particularly useful if you want certain columns aligned or colored differently, as, without this, you would need to target individual cells.
<table> <colgroup> <col> <col class="alternative"> <col> </colgroup> <tr> <td>This</td> <td>That</td> <td>The other</td> </tr> <tr> <td>Ladybird</td> <td>Locust</td> <td>Lunch</td> </tr> </table>
In this example the styles of the CSS class “alternative” will be applied to the second column, or the second cell in every row.
You can also use the
span attribute in a similar way to
colspan. Using it with the
colgroup tag will define the number of rows that the column group will belong to, for example
<colgroup span="2"></colgroup> would group the first two columns. Using
span in the
col tag is usually more useful, and could, for example, be applied to the above example like this:
<table> <colgroup> <col> <col span="2" class="alternative"> </colgroup> <!-- and so on -->
This would apply “alternative” to the last two columns.
A brief and easy accessibility consideration is to apply a caption to the table. The
caption element defines the caption and should be used straight after the opening
<table> <caption>Locust mating habits</caption> <!-- etc. -->
Headers and Footers
tbody allow you to separate the table into header, footer and body, which can be handy when dealing with larger tables.
thead needs to come first,
tfoot can, in fact come before a
tbody (and you can have more than one
tbody, if it takes your fancy) although browsers will render the
tfoot element at the bottom of the table.
<table> <thead> <tr> <td>Header 1</td> <td>Header 2</td> <td>Header 3</td> </tr> </thead> <tfoot> <tr> <td>Footer 1</td> <td>Footer 2</td> <td>Footer 3</td> </tr> </tfoot> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> <!-- etc. --> </tbody> </table>