Sub topic 2
Naming and Structuring HTML Tables
Assume you know basic HTML elements and attributes, plus basic CSS selectors. A table is appropriate when data has meaningful relationships across both rows and columns.
Naming a Table with `caption`
The caption element gives a table a visible name. Place it immediately inside table, before thead, tbody, or tfoot. A caption helps every reader understand the table’s purpose.
<table>
<caption>Monthly project expenses in dollars</caption>
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Hosting</th>
<td>80</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Total</th>
<td>80</td>
</tr>
</tfoot>
</table>Grouping Rows
Use thead for column headings, tbody for the main data, and tfoot for summaries such as totals. These elements describe the table’s structure. They also help browsers, assistive technology, and CSS target different sections.
A table can contain multiple tbody elements when the rows represent separate groups.
Merging Cells
The colspan attribute makes one cell cover multiple columns. The rowspan attribute makes it cover multiple rows.
<table>
<caption>Workshop schedule</caption>
<tr>
<th scope="col">Day</th>
<th scope="col">Morning</th>
<th scope="col">Afternoon</th>
</tr>
<tr>
<th scope="row">Monday</th>
<td colspan="2">HTML workshop</td>
</tr>
</table>Every row must still form a valid grid. A cell with colspan="2" counts as two columns. Incorrect spans can shift later cells into the wrong columns.
Making Tables Accessible with `scope`
Use th for headers and td for data. The scope attribute states whether a header describes a column or a row:
scope="col"labels cells below it.scope="row"labels cells beside it.
For simple tables, this creates a clear relationship for screen readers. Complex multi-level headers may require id on each header and matching headers values on data cells.
Exercise
Which attributes make a cell span two columns and identify a row header?
Show answer
Use colspan="2" for the spanning cell and scope="row" on the row’s th.