Use the th element to specify row and column headers in data tables

When using the HTML table to mark up tabular data, remember to use th elements for cells that provide header information for rows or columns.

In addition to using th elements for header cells, you should also use the scope or headers attributes to tell user agents, primarily screen readers and other assistive technology, which header cells provide header information for any given data cell.

Explicitly associating header cells with data cells isn’t strictly necessary for very simple tables that only have one row or column of headers, but it doesn’t hurt to get in the habit of always doing so.

Here is a simple example of header cells and the scope attribute:

  1. <table>
  2. <caption>Company data</caption>
  3. <thead>
  4. <tr>
  5. <th scope="col">Company name</th>
  6. <th scope="col">Number of employees</th>
  7. <th scope="col">Year founded</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th scope="row">ACME Inc</th>
  13. <td>1000</td>
  14. <td>1947</td>
  15. </tr>
  16. <tr>
  17. <th scope="row">XYZ Corp</th>
  18. <td>2000</td>
  19. <td>1973</td>
  20. </tr>
  21. </tbody>
  22. </table>

For more complex tables you may need to use the headers attribute instead, which makes things a bit more… complex. You first need to give each header cell an id. Next, give each data cell a headers attribute with a space-separated list of the id:s of the cells that provide header information for it.

Here is how the same table as above would be marked up with headers and id instead of scope:

  1. <table>
  2. <caption>Company data</caption>
  3. <thead>
  4. <tr>
  5. <th id="name">Company name</th>
  6. <th id="employees">Number of employees</th>
  7. <th id="founded">Year founded</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th id="acme" headers="name">ACME Inc</th>
  13. <td headers="acme employees">1000</td>
  14. <td headers="acme founded">1947</td>
  15. </tr>
  16. <tr>
  17. <th id="xyz" headers="name">XYZ Corp</th>
  18. <td headers="xyz employees">2000</td>
  19. <td headers="xyz founded">1973</td>
  20. </tr>
  21. </tbody>
  22. </table>

Further reading: Bring on the tables.

This post is a Quick Tip. Background info is available in Quick Tips for web developers and web designers.

Posted on October 28, 2009 in (X)HTML, Accessibility, Quick Tips

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.