Data Tables: Best Practice
The elements colgroup and col let you group together and target columns within your table for styling. Unfortunately, styling those elements is not consistently supported by major browsers like Firefox and IE6/IE7. We will get to that in a second. For now, we would like to group the first two columns together and last two columns together, as they include similar data (digits) to be able to style them later.
<table summary="This table displays the results of the » Cost of Living Survey 2007, ranking cities worldwide."> <caption>Cost of Living Survey - Worldwide Ranking 2007 (including housing)</caption> <colgroup id="rankings" span="2" /> <colgroup span="2" /> <colgroup id="scores" span="2" /> <thead> ... </tbody> </table>
While we are at it, we can use the scope attribute for the th element to tell non-visual user agents for which set of data this element provides header information. We do this as follows:
... <thead> <tr> <th scope="colgroup" colspan="2">Rankings</th> <th scope="colgroup" colspan="2">Location</th> <th scope="colgroup" colspan="2">Cost of Living Index</th> </tr> <tr> <th scope="col">March 2007</th> <th scope="col">March 2006</th> <th scope="col">City</th> <th scope="col">Country</th> <th scope="col">March 2007</th> <th scope="col">March 2006</th> </tr> </thead> ...
Please check out the demo page for adding accessibility and styling preparation.
Finishing Touches
We now have the markup in place, but the whole thing lacks a bit of styling. To make the table more legible, it is considered good practice to use a different background color on every other table row. To apply this background color, we need to add class=”odd” to the first, third, fifth etc. table row:
<tr class="odd"> <td>1</td> <td>1</td> <td>Moscow</td> <td>Russia</td> <td>134.4</td> <td>123.9</td> </tr>
In addition to that, we want to:
- Format the caption and the footer
- Style the headers differently than the rest of the table
- Add borders to the column groups and the table itself
- Hovering over a table row should apply different background color and font color to put emphasis on the current row
CSS to the rescue. As stated above, styling columns and column groups is not consistently supported by some major browsers. I found the following CSS issues:
- IE6/IE7: border CSS property not supported for colgroup and col
- Firefox: text-align and width not supported for colgroup and col
Please have a look at the final result. Feedback highly appreciated.
Further reading
- Tables Specification by the W3C
- Christian Heilmann’s CSS Table Gallery
- HTML, CSS and Tables: The Beauty of Data
- Creating Accessible Tables at WebAIM
- Bring on the tables by Roger Johannson
Page 2 of 3 | Previous page | Next page