Sub topic 13
Tables for Tabular Data
This chapter assumes you can write a complete HTML document, nest elements validly, and use attributes. It covers how to mark up a data table, how header cells connect to data cells, and the mistakes that break tables for real users.
When to Use a Table
A table presents data that has meaning in two dimensions: rows and columns. A schedule, a price list, and a set of measurements are all tabular. A table is not a layout tool. Older sites used tables to position page regions, but that makes pages hard to read with a screen reader and hard to adapt to small screens. Use semantic elements such as header, main and aside for layout, and CSS for positioning.
A quick test: if you could sensibly ask "what is the value in row X, column Y?", you have a table.
The Core Elements
A table is built from a small set of elements, each with a clear job.
| Element | Purpose |
|---|---|
| `table` | The container for the whole table |
| `caption` | A title that describes the table |
| `thead` | Groups the header row or rows |
| `tbody` | Groups the main data rows |
| `tfoot` | Groups summary rows, such as totals |
| `tr` | One table row |
| `th` | A header cell |
| `td` | A data cell |
Here is a minimal accessible table.
<table>
<caption>Weekly study hours</caption>
<thead>
<tr>
<th scope="col">Day</th>
<th scope="col">Hours</th>
</tr>
</thead>
<tbody>
<tr>
<td>Monday</td>
<td>2</td>
</tr>
<tr>
<td>Tuesday</td>
<td>1</td>
</tr>
</tbody>
</table>The structure reads from the outside in. The table holds a caption, then a thead and a tbody. Each group holds tr rows, and each row holds cells. Cells are always direct children of tr. Rows are children of thead, tbody, tfoot, or directly of table.
The Caption
The caption element must be the first child of table. It gives the table a visible title and also serves as its accessible name. Screen reader users can hear the caption and decide whether to read the table at all.
A caption is better than a heading placed just above the table, because the caption is programmatically tied to the table. Keep it short and specific. "Weekly study hours" tells the reader more than "Table 1".
Header Cells and the scope Attribute
The th element marks a cell as a header for other cells. Browsers usually show th content bold and centered, but the visual style is not the point. The point is the relationship: a screen reader can announce "Hours, Monday, 2" when a user lands on a data cell, because the th cells are associated with it.
Browsers can often guess the association for simple tables. The scope attribute removes the guesswork. It has these common values:
col: the header applies to the cells below it in its column.row: the header applies to the cells to its right in its row.colgroupandrowgroup: the header applies to a group of columns or rows.
A table can have row headers as well as column headers. A table of products with prices might put the product name in a th scope="row" so that each row is labeled.
<table>
<caption>Fruit prices per kilogram</caption>
<thead>
<tr>
<th scope="col">Fruit</th>
<th scope="col">Price (USD)</th>
<th scope="col">Origin</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Apples</th>
<td>3.20</td>
<td>Poland</td>
</tr>
<tr>
<th scope="row">Bananas</th>
<td>1.80</td>
<td>Ecuador</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Average</th>
<td>2.50</td>
<td></td>
</tr>
</tfoot>
</table>Notice that the empty cell in the footer is still written out. Every row must account for every column, or the grid becomes ragged.
Row Groups: thead, tbody and tfoot
The three grouping elements are optional but worth using. They give the table structure that assistive technology and CSS can use. For example, CSS can style all of thead at once, and browsers may repeat thead and tfoot on each printed page of a long table.
Some rules:
- Use at most one
theadand onetfootper table. You may use severaltbodyelements to divide data into sections. - If you write
thead,tbodyortfoot, put all rows inside one of them. Mixing grouped and ungrouped rows is invalid. - The order in the source is
caption,colgroupif any,thead,tbody(ortrrows), thentfoot. - If you omit
tbodyand writetrelements directly intable, the browser inserts atbodyin the DOM. This matters when you select elements in CSS or JavaScript, because a selector liketable > trwill not match.
Spanning Cells with colspan and rowspan
Sometimes one cell must cover several columns or rows. Two attributes do this:
colspan="n"makes a cell stretch acrossncolumns.rowspan="n"makes a cell stretch downnrows.
<table>
<caption>Class timetable</caption>
<thead>
<tr>
<th scope="col">Time</th>
<th scope="col">Monday</th>
<th scope="col">Tuesday</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">09:00</th>
<td rowspan="2">Workshop (two hours)</td>
<td>Lecture</td>
</tr>
<tr>
<th scope="row">10:00</th>
<td>Lab</td>
</tr>
<tr>
<th scope="row">11:00</th>
<td colspan="2">Open study</td>
</tr>
</tbody>
</table>When a cell spans, the cells it covers are left out of later rows or columns. In the second row above, only two cells are written (th and one td), because the Monday slot is already filled by the rowspan. Count carefully: each row must add up to the same number of columns once spans are included.
Spans also make tables harder for screen reader users to navigate. Use them only when the data truly needs them. If you find yourself building complex nested headers, consider splitting the data into two simpler tables.
Grouping Columns
The colgroup and col elements describe columns as a unit. They sit after caption and before thead. Their main use is applying a few styles to a whole column, such as a background color.
<table>
<caption>Quarterly sales</caption>
<colgroup>
<col>
<col span="2" class="current-year">
</colgroup>
<thead>
<tr>
<th scope="col">Region</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">North</th>
<td>120</td>
<td>135</td>
</tr>
</tbody>
</table>col is a void element, so it has no end tag. Only a small set of CSS properties (border, background, width, visibility) apply to columns.
Common Errors
These mistakes appear often and each has a clear fix.
- Using a table for layout. Replace it with semantic elements and CSS.
- Using
tdwith bold text instead ofth. The look matches, but the header relationship is lost. Useth. - Missing
caption. The table has no accessible name. Add one. - Rows with different column counts. Count cells and spans. Browsers render the table anyway, but the grid is misaligned and validators report it.
- Putting content directly in
tableortr. Only the table elements listed above are allowed as children. Text or adivplaced between rows is invalid and the browser moves it out of the table when it parses the page. - Styling with obsolete attributes. Attributes such as
border,cellpadding,cellspacingandalignare obsolete. Use CSS:border,padding,border-collapseandtext-align. - Empty
thcells with no purpose. A blank corner cell is sometimes needed in a table with both row and column headers. If you leave one, keep it as atdor aththat is intentionally empty, and make sure the rest of the headers still havescope.
Responsive Considerations
Wide tables overflow narrow screens. The usual fix is to wrap the table in a container and let that container scroll horizontally, rather than changing the table's own display. Changing display on table elements with CSS can remove their table semantics in some browsers, which breaks the header associations you worked to add.
Checking Your Table
After writing a table, run three checks:
- Validate the HTML. A validator flags rows with the wrong number of cells and content in the wrong place.
- Open the browser developer tools and inspect the table. Confirm the
tbodyand other elements appear where you expect. - Tab through the page with a screen reader, or read the markup aloud: for each data cell, can you name its row and column header?
Exercise
A table has a thead row with three th cells. In the body, the first row has a td with rowspan="2" followed by two td cells. How many cells should the second body row contain, and why?
Show answer
Two cells. The first column is already covered by the rowspan from the row above, so the second row only needs to supply the remaining two columns. Each row must still add up to three columns once spans are counted.
Exercise
Why is it better to write <th scope="col">Hours</th> than <td><strong>Hours</strong></td> for a column heading?
Show answer
The th element, with scope, tells browsers and assistive technology that the cell is a header for the cells below it, so a screen reader can announce "Hours" when a user reads a data cell. A bold td only looks like a header and carries no such relationship.
Exercise
You write tr elements directly inside table, with no tbody. Your CSS selector table > tbody > tr does not match in the browser, but table > tr does not match either. Which is it, and why?
Show answer
table > tbody > tr matches. The HTML parser automatically inserts a tbody around the loose rows in the DOM, so table > tr finds nothing. Writing the tbody yourself avoids the surprise.