Sub topic 1
HTML Tables: When a Table Is the Right Choice
Prerequisites
This chapter assumes you know basic HTML structure, elements, attributes, and CSS selectors.
When a table is the right choice
Use an HTML table when information has a meaningful relationship across both rows and columns. A reader should be able to compare values by following a row or a column.
Examples include a monthly budget, a class schedule, or product specifications. Use lists, sections, or CSS Grid for content that does not represent row-and-column data. Do not use a table only to position parts of a page.
Rows and cells: table, tr, and td
The table element contains the complete data set. A tr element represents one table row. A td element represents a regular data cell. In a simple table, each row should contain the same number of columns.
<table>
<tr>
<td>Oslo</td>
<td>700000</td>
</tr>
<tr>
<td>Riga</td>
<td>605000</td>
</tr>
</table>This markup creates the grid, but it does not identify what each value means. A screen reader may announce the cell values without useful column context.
Header cells with th
A th element is a header cell. It labels a column or row and gives the data a navigable structure. Use scope="col" for a column header and scope="row" for a row header.
<table>
<tr>
<th scope="col">City</th>
<th scope="col">Population</th>
</tr>
<tr>
<th scope="row">Oslo</th>
<td>700000</td>
</tr>
<tr>
<th scope="row">Riga</th>
<td>605000</td>
</tr>
</table>The first row labels columns. The first cell in each later row labels that row. This relationship lets assistive technology provide context while a user moves between cells.
Exercise
Should a two-column list of unrelated links use a table?
Show answer
No. If the columns do not describe related data, use a list or another suitable layout.