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:
<table>
<caption>Company data</caption>
<thead>
<tr>
<th scope="col">Company name</th>
<th scope="col">Number of employees</th>
<th scope="col">Year founded</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">ACME Inc</th>
<td>1000</td>
<td>1947</td>
</tr>
<tr>
<th scope="row">XYZ Corp</th>
<td>2000</td>
<td>1973</td>
</tr>
</tbody>
</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
:
<table>
<caption>Company data</caption>
<thead>
<tr>
<th id="name">Company name</th>
<th id="employees">Number of employees</th>
<th id="founded">Year founded</th>
</tr>
</thead>
<tbody>
<tr>
<th id="acme" headers="name">ACME Inc</th>
<td headers="acme employees">1000</td>
<td headers="acme founded">1947</td>
</tr>
<tr>
<th id="xyz" headers="name">XYZ Corp</th>
<td headers="xyz employees">2000</td>
<td headers="xyz founded">1973</td>
</tr>
</tbody>
</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.