Skip to content

Lesson 7 of 52HTML

Tables

Mark up tabular data with headers, captions, scope and spanning cells so it reads well for everyone.

17 min read0/6 questions

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).

Quick check
Which of these should be built with an HTML table?
Need a nudge? A hint rules out a wrong answer.

The building blocks

A table is built row by row. Each row holds cells, and each cell is either a header or data.

ElementJob
tableWraps the whole table
captionThe table's title. Must be the first child of table
theadThe group of header rows at the top
tbodyThe group of rows holding the data
tfootOptional summary rows, such as totals
trOne table row
thA header cell (bold and centred by default)
tdA data cell
The shape of a table
tablecaptionththtrtheadthtdtrthtdtrtbodyroot

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.

HTML & CSS
<style> table { border-collapse: collapse; } th, td { border: 1px solid #bbb; padding: 6px 12px; text-align: left; } thead th { background: #f0f0f0; } caption { font-weight: 700; padding-bottom: 8px; }</style><table> <caption>Plans and prices</caption> <thead> <tr> <th scope="col">Plan</th> <th scope="col">Storage</th> <th scope="col">Price per month</th> </tr> </thead> <tbody> <tr> <th scope="row">Free</th> <td>5 GB</td> <td>0 EUR</td> </tr> <tr> <th scope="row">Pro</th> <td>100 GB</td> <td>8 EUR</td> </tr> </tbody></table>

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 the pairs0/5 matched

Match each element or attribute to its job.

Choose an item, then its match on the other side.

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.

HTML & CSS
<style> table { border-collapse: collapse; } th, td { border: 1px solid #bbb; padding: 6px 12px; text-align: center; } thead th { background: #f0f0f0; } .lunch { background: #fff6d6; }</style><table> <caption>Class timetable</caption> <thead> <tr> <th scope="col">Time</th> <th scope="col">Mon</th> <th scope="col">Tue</th> <th scope="col">Wed</th> </tr> </thead> <tbody> <tr> <th scope="row">09:00</th> <td rowspan="2">Science lab</td> <td>Maths</td> <td>Art</td> </tr> <tr> <th scope="row">10:00</th> <td>History</td> <td>Music</td> </tr> <tr> <th scope="row">12:00</th> <td colspan="3" class="lunch">Lunch</td> </tr> </tbody></table>

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.

Predict the outputHTML

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>
Need a nudge? Hints walk you through it.

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: collapse merges neighbouring borders into single lines.
  • Padding on th and td gives 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-child in 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:

HTML & CSS
<style> .scroll { overflow-x: auto; max-width: 260px; border: 2px dashed #bbb; } table { border-collapse: collapse; } th, td { border: 1px solid #bbb; padding: 6px 10px; white-space: nowrap; } td { text-align: right; } tbody tr:nth-child(even) { background: #f5f5f5; }</style><div class="scroll"> <table> <caption>Average rainfall in mm (rounded)</caption> <thead> <tr><th scope="col">City</th><th scope="col">Jan</th><th scope="col">Feb</th><th scope="col">Mar</th><th scope="col">Apr</th></tr> </thead> <tbody> <tr><th scope="row">Lisbon</th><td>100</td><td>89</td><td>62</td><td>65</td></tr> <tr><th scope="row">London</th><td>55</td><td>41</td><td>42</td><td>44</td></tr> <tr><th scope="row">Oslo</th><td>49</td><td>36</td><td>47</td><td>41</td></tr> </tbody> </table></div>

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" plus aria-labelledby pointing at the caption gives that focus stop a name: "Average rainfall in mm, region". Without a name, a focusable div is 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.

HTML & CSS
<style> .wrap { max-width: 320px; max-height: 220px; overflow: auto; border: 1px solid #999; } .wrap:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; } table { border-collapse: separate; border-spacing: 0; } th, td { padding: 6px 12px; white-space: nowrap; border-bottom: 1px solid #ccc; border-right: 1px solid #ccc; background: white; } td { text-align: right; font-variant-numeric: tabular-nums; } thead th { position: sticky; top: 0; z-index: 1; background: #f0f0f0; } tbody th { position: sticky; left: 0; text-align: left; } thead th:first-child { left: 0; z-index: 2; }</style><div class="wrap" role="region" aria-labelledby="sales-caption" tabindex="0"> <table> <caption id="sales-caption">Units sold per region</caption> <thead> <tr><th scope="col">Region</th><th scope="col">Jan</th><th scope="col">Feb</th><th scope="col">Mar</th><th scope="col">Apr</th><th scope="col">May</th><th scope="col">Jun</th></tr> </thead> <tbody> <tr><th scope="row">North</th><td>1,204</td><td>1,180</td><td>1,342</td><td>1,111</td><td>1,276</td><td>1,390</td></tr> <tr><th scope="row">South</th><td>981</td><td>1,020</td><td>1,005</td><td>1,118</td><td>1,207</td><td>1,301</td></tr> <tr><th scope="row">East</th><td>744</td><td>802</td><td>790</td><td>811</td><td>876</td><td>901</td></tr> <tr><th scope="row">West</th><td>1,511</td><td>1,488</td><td>1,602</td><td>1,577</td><td>1,640</td><td>1,712</td></tr> <tr><th scope="row">Central</th><td>655</td><td>701</td><td>688</td><td>720</td><td>745</td><td>760</td></tr> <tr><th scope="row">Islands</th><td>212</td><td>198</td><td>240</td><td>251</td><td>266</td><td>301</td></tr> <tr><th scope="row">Online</th><td>3,050</td><td>3,210</td><td>3,402</td><td>3,388</td><td>3,515</td><td>3,690</td></tr> </tbody> </table></div>

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: sticky on the th cells, not on tr. Sticky on thead now 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. Use border-collapse: separate with border-spacing: 0 and 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.
Stacking the layers of a sticky table
  1. Corner cellsticky top and left, z-index: 2
  2. Header rowthead th: sticky top, z-index: 1
  3. First columntbody th: sticky left
  4. Body cellsscroll freely underneath

Body cells scroll in both directions. Everything above has to cover them, so every sticky cell needs a solid background.

1/4
Quick check
A table sits inside 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?
Need a nudge? A hint rules out a wrong answer.

Sortable columns

Data tables at work are usually sortable: click "Price" to sort by price, click again to reverse. Three details make it accessible.

  1. A real button inside the th. Clicking a bare th with a click handler cannot be reached with the keyboard and is not announced as interactive. A button inside the header cell gets focus, Enter and Space for free, and the header cell keeps its job of labelling the column.
  2. aria-sort on the sorted th, with the value ascending or descending. 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.
  3. Say what happened. Screen readers announce aria-sort inconsistently when it changes, so many teams also update a visually hidden live region or the caption text: "Sorted by price, ascending".
HTML & CSS
<style> table { border-collapse: collapse; min-width: 300px; } th, td { border: 1px solid #bbb; padding: 6px 10px; text-align: left; } td.num { text-align: right; font-variant-numeric: tabular-nums; } th button { all: unset; cursor: pointer; font-weight: 700; } th button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; } th[aria-sort="ascending"] button::after { content: " \2191"; } th[aria-sort="descending"] button::after { content: " \2193"; } .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }</style><table id="books"> <caption>Books in stock</caption> <thead> <tr> <th scope="col"><button type="button" data-key="title">Title</button></th> <th scope="col"><button type="button" data-key="price" data-num>Price (EUR)</button></th> <th scope="col"><button type="button" data-key="stock" data-num>Stock</button></th> </tr> </thead> <tbody></tbody></table><p class="visually-hidden" aria-live="polite" id="status"></p><script> const rows = [ { title: "Dune", price: 12.5, stock: 4 }, { title: "Emma", price: 7.99, stock: 11 }, { title: "Beloved", price: 10, stock: 0 }, { title: "Ulysses", price: 15.2, stock: 3 }, ]; const body = document.querySelector("#books tbody"); function render() { body.innerHTML = rows.map((r) => `<tr><th scope="row">${r.title}</th><td class="num">${r.price.toFixed(2)}</td><td class="num">${r.stock}</td></tr>` ).join(""); } for (const button of document.querySelectorAll("#books th button")) { button.addEventListener("click", () => { const th = button.parentElement; const next = th.getAttribute("aria-sort") === "ascending" ? "descending" : "ascending"; for (const other of document.querySelectorAll("#books th")) other.removeAttribute("aria-sort"); th.setAttribute("aria-sort", next); const key = button.dataset.key; const dir = next === "ascending" ? 1 : -1; rows.sort((a, b) => (button.hasAttribute("data-num") ? a[key] - b[key] : a[key].localeCompare(b[key])) * dir); render(); document.getElementById("status").textContent = `Sorted by ${button.textContent}, ${next}`; }); } render();</script>

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.

Quick check
Which markup gives a sortable 'Price' column that is sorted ascending?
Need a nudge? A hint rules out a wrong answer.
Put it in order6 steps

Put the parts of a table in source order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.