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.
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 rowspan
and colspan
. Using it with thecolgroup
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.
Caption interlude
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
tag.
<table>
<caption>Locust mating habits</caption>
<!-- etc. -->
Headers and Footers
thead
, tfoot
and tbody
allow you to separate the table into header, footer and body, which can be handy when dealing with larger tables.
Whereas
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>