You can include a caption for a table by using the <caption> element. The <caption> element occurs just after the starting tag of <table> element. The content of the table element is shown in browsers and read aloud by screen readers. Users having screen readers can figure out what the table is about by hearing the content of the <caption> element. Hence this element is essential for accessibility.
<table> <caption>This is a caption.</caption> </table>
Screen readers use the <th> elements to make the associations for the data in a table. So it is recommended to have headers for tables. In order to guide the screen readers to make the correct associations for data, we use the scope attribute. If the header is for the column then the value for scope is col. For rows, the scope attribute takes the value row. Using the scope attribute for headers improves the accessibility of the table for the users of screen readers. This method of using scope attribute results in cleaner code than other methods.
<table> <tr> <th scope="row">Characters</th> <td>Luke Skywalker</td> <td>Han Solo</td> <td>Leia Organa</td> </tr> <tr> <th scope="row">Actors</th> <td>Mark Hamill</td> <td>Harrison Ford</td> <td>Carrie Fisher</td> </tr> </table>
A table can be split into three sections using the <thead>, <tbody> and <tfoot> elements.
- The head section can have all of the column headers which typically come in the first table row. If the table uses <col> and <colgroup> elements, then the <thead> element can come after these elements.
- The foot section of the table can hold the final row. For some tables, the final row usually has some aggregate data based on the other rows. In this situation using the <tfoot> element makes sense.
- The rest of the rows should be inside the <tbody> element. If it is not present then some browsers assume all the rows to be part of the <tbody> element.
While these elements do not offer anything special for screen readers, they do have some interesting uses for normal users. Using some CSS styles the head and foot sections can be highlighted to make them stand out. These sections can be made fixed while the content can be made scrollable. If a table spans multiple pages, then the head section can be made to repeat.