Of all the tags used with tables, including those for accessibility, perhaps the most neglected is the col
element. The easiest way to describe col
is by making a comparison to the div
tag: col
is an element that controls the appearance of other content, while the col
tag does not appear on the page itself (or at least not without CSS applied). col
allows us to avoid the need to repeatedly apply classes to induvidual table cells.
Name | Country | Best Time |
---|---|---|
Average Time | 9.66 seconds | |
Usain Bolt | Jamaica | 9.58 seconds |
Tyson Gay | United States | 9.69 seconds |
Asafa Powell | Jamaica | 9.72 seconds |
The <col>
tag is integrated into the table structure just after the <caption>
. (Note that I’ve removed closing tags that are optional in HTML5 to save space – in XHTML, an opening <col>
tag should be matched with a closing </col>
).
<table id=sprinters>
<caption>World’s Fastest 100m Sprinters, 2012</caption>
<col><col><col>
<thead>
<tr>
<th>Name
<th>Country
<th>Best Time
</thead>
<tfoot>
<tr>
<td colspan="2">Average Time
<td>9.66 seconds
</tfoot>
<tbody>
<tr>
<td>Usain Bolt
<td>Jamaica
<td>9.58 seconds
<tr>
<td>Tyson Gay
<td>United States
<td>9.69 seconds
<tr>
<td>Asafa Powell
<td>Jamaica
<td>9.72 seconds
</tbody>
</table>
This markup has the following CSS applied:
#sprinters {
border-collapse: collapse;
}
#sprinters caption {
font-size: larger;
}
#sprinters td, #sprinters th {
padding: .5rem;
}
#sprinters tfoot tr td {
border-top: 1px solid #000;
}
#sprinters col:last-child {
background: #ddd;
}
#sprinters thead {
background: #000;
color: #fff;
}
The number of <col>
elements must match the number of table cells in each row. You can stretch a <col>
to take command of more columns with the <span>
attribute:
<col span="2"><col>
The “count” of <col>
elements is now equal to 3, and any style applied to the first <col>
element will control the appearance of the first two table columns.
Table columns can be grouped together using the colgroup
element:
<colgroup>
<col><col>
</colgroup>
<col>
Both <col>
and <colgroup>
can have styles applied to enhance the appearance of tables.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.