Lesson 7 of 52HTML
Tables
Mark up tabular data with headers, captions, scope and spanning cells so it reads well for everyone.
Some information is naturally a grid: a train timetable, a price comparison, a league table, a weekly class schedule. HTML tables exist for exactly that. A well built table lets a sighted reader scan across rows and down columns, and lets a screen reader user hear "Pro plan, Storage, 100 GB" instead of a stream of disconnected numbers. This lesson shows when a table is the right tool, the handful of elements you need, and how to make cells span more than one row or column.
Tables are for data, not layout
Long ago, before CSS could arrange a page, people built entire layouts out of tables: a header row, a sidebar cell, a content cell. That is now a mistake. Layout tables confuse screen readers (they announce "table with 3 columns" around your navigation), they are hard to make responsive, and they mix structure with appearance.
The test is simple: would this content make sense in a spreadsheet? If each row is a thing and each column is a property of that thing, use a table. If you just want boxes side by side, use CSS (Flexbox and Grid, later in this course).
The building blocks
A table is built row by row. Each row holds cells, and each cell is either a header or data.
| Element | Job |
|---|---|
table | Wraps the whole table |
caption | The table's title. Must be the first child of table |
thead | The group of header rows at the top |
tbody | The group of rows holding the data |
tfoot | Optional summary rows, such as totals |
tr | One table row |
th | A header cell (bold and centred by default) |
td | A data cell |
Notice that th can also start a body row. In a price table, the plan name at the start of each row is a header for that row, so it is a th, not a td.
Preview
Add a third plan by copying one tr block and changing the values. Then delete the line border-collapse: collapse; and see why almost every table stylesheet starts with it: without it, each cell draws its own border with a gap between them. Finally, move the caption below the thead and notice the browser no longer treats it as a caption.
Captions and scope
A caption is the table's name. It shows above the table by default and is the first thing a screen reader announces, so the listener knows what they are about to navigate. Write it like a heading: "Plans and prices", "Train times, Berlin to Hamburg".
The scope attribute on a th says which cells it labels:
scope="col"means "I am the header for the cells below me".scope="row"means "I am the header for the cells to my right".
In a simple table with one header row, browsers often work this out on their own. Adding scope removes the guessing, costs a few characters, and is a habit worth having from day one. When a screen reader user moves to the "100 GB" cell, they hear "Pro, Storage, 100 GB" because of these links.
Match each element or attribute to its job.
Spanning cells: colspan and rowspan
Sometimes one cell needs to cover more than one column or row. Think of a school timetable where lunch spans every day, or a header like "Weekend" sitting above both "Saturday" and "Sunday".
colspan="2"makes a cell stretch across two columns.rowspan="2"makes a cell stretch down two rows.
The trick is counting. Every row must still add up to the same number of columns. When a cell spans, you remove the cells it covers. A rowspan cell also eats a slot in the rows below it, so those rows get one fewer cell.
Preview
Change colspan="3" to colspan="2" and an empty gap appears at the end of the lunch row, because the row now adds up to three columns instead of four. Then add an extra td to the 10:00 row and see it stick out as a fifth column: the science lab's rowspan already fills Monday at 10:00.
A table has 4 columns. How many td or th elements does this row need?
<tr> <th scope="row">Total</th> <td colspan="2">...</td> ... </tr>
Totals with tfoot
Many tables end with a summary: a total, an average, a grand sum. Put those rows in a tfoot after the tbody. Browsers draw it at the bottom, and screen readers and print styles can treat it as a footer for the data rather than one more data row. Long tables printed across several pages can even repeat the thead and tfoot on each page.
<tfoot>
<tr>
<th scope="row">Total</th>
<td>105 GB</td>
<td>8 EUR</td>
</tr>
</tfoot>How a screen reader moves through a table
It helps to know what your markup is for. When a screen reader user reaches a table, they first hear something like "Plans and prices, table, 3 columns, 3 rows". That is the caption and the structure. They then move cell by cell with special table keys (in VoiceOver and NVDA, combinations with the arrow keys). Moving right along a row, they hear the column header and then the value: "Storage, 100 GB". Moving down a column, they hear the row header: "Pro, 100 GB". Without th elements, all they would hear is "100 GB" and they would have to remember which row and column they were in, a bit like reading a spreadsheet with the headers cut off.
Use spans sparingly. A table full of merged cells is hard for everyone to follow and harder still for screen readers. If you find yourself merging a lot, two simpler tables are often clearer than one clever one.
Styling and small screens
A few CSS habits make tables much easier to read:
border-collapse: collapsemerges neighbouring borders into single lines.- Padding on
thandtdgives the numbers room to breathe. - Right-align number columns (
text-align: right) so the digits line up. - Light stripes with
tbody tr:nth-child(even)help the eye follow a long row. You will meet:nth-childin the selectors lesson.
Wide tables do not fit on phones. The simplest fix that keeps the table intact is to wrap it in a container that can scroll sideways:
Preview
Scroll the table sideways inside the dashed box. Change max-width: 260px to max-width: 600px and the scrollbar disappears because everything fits. Change nth-child(even) to nth-child(odd) to move the stripes.
Responsive data tables without breaking semantics
The scroll container above works with a mouse or a finger, but a keyboard user cannot scroll it: a plain div never receives focus, so the arrow keys scroll the page instead. Screen reader users also get no hint that the region scrolls. The production version adds three attributes:
<div class="scroll" role="region" aria-labelledby="rain-caption" tabindex="0">
<table>
<caption id="rain-caption">Average rainfall in mm (rounded)</caption>
...
</table>
</div>tabindex="0"makes the container focusable, so Tab reaches it and the arrow keys scroll it. Recent Chrome versions make a scroll container focusable by default when nothing inside it can take focus, but you cannot count on every browser doing so, and automated checkers such as axe flag a scrollable region nobody can focus.role="region"plusaria-labelledbypointing at the caption gives that focus stop a name: "Average rainfall in mm, region". Without a name, a focusabledivis just an unexplained stop in the tab order.- Give the container a visible focus style, as for any focusable element.
Only add these when the table can actually overflow. A focus stop that does nothing is a small annoyance for every keyboard user.
Why card layouts are risky
The other common approach turns each row into a card on small screens: set display: block (or grid, or flex) on table, tr and td, hide the header row, and show each column's name with td::before { content: attr(data-label); }. It looks good. It can also quietly delete the table for assistive technology.
Browsers build the accessibility tree partly from CSS. When you change the display of table elements, some browser and screen reader combinations have stopped exposing them as a table at all: no rows, no columns, no header announcements, just a stream of text. Safari has been the usual offender, and behaviour has changed between versions, so you cannot assume the current one is fine. Hiding thead with display: none also removes the headers from the accessibility tree, and text from ::before is announced inconsistently.
If you do build cards, put the semantics back explicitly and test with a real screen reader:
<table role="table">
<thead role="rowgroup"><tr role="row"><th role="columnheader">City</th>...</tr></thead>
<tbody role="rowgroup"><tr role="row"><th role="rowheader">Lisbon</th><td role="cell">100</td>...</tr></tbody>
</table>Normally this is the "redundant ARIA" that linters warn about, and here it is deliberate: it restores the roles that CSS took away. A simpler choice, and often a better one, is to keep a real table, make it scroll, and pin the first column so each row stays identifiable while you scroll. That is the next section.
Sticky headers and first column
On a long or wide table, people lose track of which column they are in once the header scrolls away. position: sticky keeps header cells in view. The rules that make it work are not obvious, which is why it is a classic "why does this not stick?" question.
Preview
Scroll down and across inside the box: the month row and the region column stay put. Press Tab to focus the box and use the arrow keys. Now remove background: white from th, td and see the body cells show through the sticky ones. Then delete max-height: 220px: the header no longer sticks when the page scrolls, because the box itself has stopped scrolling vertically.
That last experiment shows the rule behind most bugs. A sticky element sticks inside its nearest scrolling ancestor, not the page. Putting overflow-x: auto on the wrapper (for horizontal scroll) makes the wrapper the scroll container in both directions, so top: 0 now means "the top of the wrapper". If the wrapper is as tall as the table, it never scrolls vertically and the header never sticks. Give the wrapper a max-height so it scrolls on its own, or drop the wrapper if the page should do the vertical scrolling.
The other rules:
- Put
position: stickyon thethcells, not ontr. Sticky ontheadnow works in current browsers too, but cells are the most reliable target. - Sticky cells need an opaque background, or the rows scroll visibly underneath them.
- With
border-collapse: collapse, borders belong to the table rather than the cells, so they scroll away from sticky cells and leave a gap. Useborder-collapse: separatewithborder-spacing: 0and draw borders on one side of each cell, as the demo does. - The corner cell is sticky in both directions and needs the highest
z-index, or the first column slides over it.
Body cells scroll in both directions. Everything above has to cover them, so every sticky cell needs a solid background.
div style='overflow-x: auto' and its thead th cells have position: sticky; top: 0. When the user scrolls the page, the header scrolls away. Why?Sortable columns
Data tables at work are usually sortable: click "Price" to sort by price, click again to reverse. Three details make it accessible.
- A real button inside the
th. Clicking a barethwith a click handler cannot be reached with the keyboard and is not announced as interactive. Abuttoninside the header cell gets focus, Enter and Space for free, and the header cell keeps its job of labelling the column. aria-sorton the sortedth, with the valueascendingordescending. Put it only on the column that is currently sorted, and remove it from the others. The ARIA authoring practices recommend one sorted header at a time.- Say what happened. Screen readers announce
aria-sortinconsistently when it changes, so many teams also update a visually hidden live region or the caption text: "Sorted by price, ascending".
Preview
Click "Price (EUR)" twice and watch the arrow and the order flip. Tab to the headers and press Enter instead of clicking. Inspect a header in DevTools and see aria-sort move from column to column. The arrows come from CSS that reads aria-sort, so the visual state cannot drift from the accessible one.
Two more details from real data tables. Right-align numbers and their headers, and use font-variant-numeric: tabular-nums so every digit has the same width and columns line up even in fonts with proportional digits. And put units in the header ("Price (EUR)") rather than in every cell, which keeps cells short and lets them sort as numbers.
Put the parts of a table in source order.
- Tap the steps below in the right order.
- table
- An element for data arranged in rows and columns. Not for page layout.
- th and td
- Header cells and data cells. A th labels other cells; a td holds a value.
- caption
- The table's title, the first child of table, announced first by screen readers.
- scope
- An attribute on th saying whether it labels a column (col) or a row (row).
- colspan and rowspan
- Attributes that let a cell stretch across several columns or down several rows.
- border-collapse
- A CSS property that merges neighbouring cell borders into single lines.
- aria-sort
- An attribute on a column header saying the table is sorted by that column, ascending or descending.
- position: sticky
- Keeps an element in view at an offset inside its nearest scrolling ancestor, used for table headers and first columns.
- tabular-nums
- A font-variant-numeric value that gives every digit the same width so numbers line up in columns.