Skip to main content

Frontend development · Intermediate · 20 min

Build a responsive HTML table

By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard and CSS Positioned Layout Level 3 · checked in Chromium with Playwright 1.65.1

You will build the Larkfield Clinic staff appointment table with real table markup, tabular numbers, a sticky header and a sticky first column inside a labelled, keyboard-focusable scroll area, so it keeps its table semantics from a desktop monitor down to a 360 pixel phone.

On this page

The reception staff at Larkfield Clinic, the community clinic whose patients book through the appointment app, need the other side of the booking flow: a list of the day's appointments they can scan between phone calls, on the desktop at the front desk and on a phone when they are away from it. The data is a grid of facts, with one row per appointment and one column per kind of fact, which is exactly what an HTML table is for.

The usual way to make a table "responsive" is to restyle every row as a card of divs, or to set display: block on the table parts. Both break what makes a table useful to someone using a screen reader: the ability to move along a row or down a column and hear which column header each cell belongs to. This tutorial keeps the real table at every width. On a narrow screen, the table scrolls sideways inside its own box, the header row stays at the top, and the time column stays pinned on the left, so a row never loses its label.

You will write the markup, style it for scanning, add the sticky parts and the scroll area, and finish with a Playwright script that checks the semantics and the layout at desktop and phone widths.

Step 1 · Write the table markup

Make a demo folder and an HTML page holding Tuesday 9 December's appointments. The 10:30 Nurse appointment for Sam Patel is the one booked through the patient app in the design series, and the clinicians and rooms match the table designed in that series: Dr Ada Okafor in Room 1, Dr Amaka Bello in Room 2 and Nurse Ruth Ellis in Room 3.

Bash
mkdir -p ~/larkfield-table-demo
cd ~/larkfield-table-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Larkfield appointments</title>
  <link rel="stylesheet" href="table.css">
</head>
<body>
  <main>
    <h1>Front desk</h1>
    <div class="table-scroll" role="region" aria-labelledby="appointments-caption" tabindex="0">
      <table class="appointments">
        <caption id="appointments-caption">Appointments, Tuesday 9 December</caption>
        <thead>
          <tr>
            <th scope="col">Time</th>
            <th scope="col">Patient</th>
            <th scope="col">Service</th>
            <th scope="col" class="num">Length (min)</th>
            <th scope="col">Clinician</th>
            <th scope="col">Room</th>
            <th scope="col">Status</th>
          </tr>
        </thead>
        <tbody>
          <tr><th scope="row">08:30</th><td>Grace Mensah</td><td>Nurse appointment</td><td class="num">15</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Seen</td></tr>
          <tr><th scope="row">08:40</th><td>Daniel Boateng</td><td>GP appointment</td><td class="num">10</td><td>Dr Amaka Bello</td><td>Room 2</td><td>Seen</td></tr>
          <tr><th scope="row">09:00</th><td>Tom Reilly</td><td>GP appointment</td><td class="num">10</td><td>Dr Ada Okafor</td><td>Room 1</td><td>Seen</td></tr>
          <tr><th scope="row">09:20</th><td>Fatima Yusuf</td><td>Blood test</td><td class="num">10</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Seen</td></tr>
          <tr><th scope="row">09:40</th><td>Kwame Asante</td><td>Vaccination</td><td class="num">15</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Arrived</td></tr>
          <tr><th scope="row">10:00</th><td>Lena Novak</td><td>Medication review</td><td class="num">20</td><td>Dr Amaka Bello</td><td>Room 2</td><td>Arrived</td></tr>
          <tr><th scope="row">10:30</th><td>Sam Patel</td><td>Nurse appointment</td><td class="num">15</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Booked</td></tr>
          <tr><th scope="row">11:00</th><td>Chidinma Okoro</td><td>GP appointment</td><td class="num">10</td><td>Dr Ada Okafor</td><td>Room 1</td><td>Booked</td></tr>
          <tr><th scope="row">12:00</th><td>Ngozi Okeke</td><td>Nurse appointment</td><td class="num">15</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Booked</td></tr>
          <tr><th scope="row">14:20</th><td>Aisha Khan</td><td>Medication review</td><td class="num">20</td><td>Dr Amaka Bello</td><td>Room 2</td><td>Booked</td></tr>
          <tr><th scope="row">15:00</th><td>Liam O'Connor</td><td>GP appointment</td><td class="num">10</td><td>Dr Ada Okafor</td><td>Room 1</td><td>Booked</td></tr>
          <tr><th scope="row">15:40</th><td>Hannah Lee</td><td>Vaccination</td><td class="num">15</td><td>Nurse Ruth Ellis</td><td>Room 3</td><td>Booked</td></tr>
        </tbody>
      </table>
    </div>
  </main>
</body>
</html>
HTML
touch table.css

Each part of the markup has a job:

  • <caption> is the table's name. Screen readers announce it when a user reaches the table, and it shows on screen, so sighted staff and screen reader users get the same title. Write it as you would a heading: what the data is and for which day.
  • <thead> and <tbody> separate the header row from the data. The sticky header in a later step targets thead th.
  • <th scope="col"> marks a column header. When a screen reader user moves along a row into a new column, the reader announces that column's header with the cell, so moving right from Service in the 10:30 row gives something like "Clinician, Nurse Ruth Ellis".
  • <th scope="row"> marks the cell that names the row. For a day list that is the time. When a user moves down a column into a new row, the reader announces that row's header with the cell, so moving down the Status column gives something like "10:30, Booked". This is also the column you will pin on a phone.
  • class="num" marks the one column that holds a quantity, so it can be aligned differently.

The div around the table, with its role, aria-labelledby and tabindex, does nothing yet. It becomes the scroll area in step 4, and step 5 explains each attribute.

Check it worked

Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). You see the browser's default table: the caption centred above it, header cells in bold and centred, and twelve rows from 08:30 to 15:40. The time in each row is bold too, because it is a th.

Step 2 · Style the table for scanning

Write the stylesheet. The colours are the Larkfield colour variables from the high-fidelity design, written as custom properties:

Bash
cd ~/larkfield-table-demo
cat > table.css <<'CSS'
:root {
  --colour-text: #1b1f24;
  --colour-text-muted: #5a6270;
  --colour-surface: #ffffff;
  --colour-canvas: #f6f7f8;
  --colour-line: #d5d9df;
  --colour-border: #7d8592;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  padding: 1rem;
  background: var(--colour-canvas);
  color: var(--colour-text);
  font-family: system-ui, sans-serif;
  line-height: 1.5;
}

.appointments {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: var(--colour-surface);
  font-variant-numeric: tabular-nums;
}

.appointments caption {
  padding: 0.75rem 1rem;
  text-align: start;
  font-size: 1.125rem;
  font-weight: 700;
}

.appointments th,
.appointments td {
  padding: 0.625rem 1rem;
  border-bottom: 1px solid var(--colour-line);
  text-align: start;
  white-space: nowrap;
}

.appointments thead th {
  background: var(--colour-canvas);
  border-bottom: 2px solid var(--colour-border);
  color: var(--colour-text-muted);
  font-size: 0.875rem;
  font-weight: 600;
}

.appointments tbody th {
  background: var(--colour-surface);
  font-weight: 600;
}

.appointments .num { text-align: end; }
CSS

The choices that matter for reading data:

  • font-variant-numeric: tabular-nums gives every digit the same width. In many fonts a 1 is narrower than a 0 by default, so times and lengths in a column wobble. With tabular figures, 10:30 sits exactly above 11:10 and the eye runs straight down the column.
  • .num right-aligns the length column, header included, so the units line up. Text stays aligned to the start. start and end rather than left and right mean the table mirrors correctly if the page is ever translated into a right-to-left language such as Arabic.
  • white-space: nowrap keeps "Nurse appointment" on one line. A wrapped cell makes rows of different heights, which is harder to scan, and a table that refuses to squeeze is what makes the scroll area in step 4 work.
  • border-collapse: separate with border-spacing: 0 looks the same as collapsed borders here. It is there for the sticky cells later: with collapsed borders, the borders belong to the table rather than the cells, and they scroll away from a sticky header instead of staying on it.
  • Header and row header cells get an opaque background. Without one, sticky cells are transparent and the rows show through them when they scroll underneath.

Check it worked

Reload. The caption is bold and aligned left above the table, the header row is grey with a darker line under it, the rows are separated by thin lines, and every value in the Length (min) column lines up on the right. Look down the Time column: the colons sit in one vertical line.

Step 3 · Keep the header row in view

On a long day the list runs past the bottom of the screen and staff lose track of which column is which. Make the header cells sticky:

Bash
cd ~/larkfield-table-demo
cat >> table.css <<'CSS'

.appointments thead th {
  position: sticky;
  top: 0;
  z-index: 2;
}
CSS

A sticky element behaves normally until its nearest scrolling ancestor scrolls it to the top offset, then it stays there until its containing block, here the table, leaves the screen. Right now nothing inside the page scrolls, so that ancestor is the browser window. Put position: sticky on the th cells, not on thead or the tr: sticky cells are the most reliable across browsers. z-index: 2 keeps the header above the body cells, which matters once the first column is sticky too.

Check it worked

Reload and make the browser window short, around 400 pixels tall, then scroll the page. The caption scrolls away, and the grey header row stops at the top of the window while the rows slide under it. It leaves when the last row has gone.

Step 4 · Let the table scroll inside its own box

Now make the window narrow, or open your browser's responsive mode at 360 pixels wide. The whole page scrolls sideways, heading included, because the table refuses to be narrower than its content. Make the wrapper the thing that scrolls instead:

Bash
cd ~/larkfield-table-demo
cat >> table.css <<'CSS'

.table-scroll {
  max-height: 70vh;
  overflow: auto;
  border: 1px solid var(--colour-line);
  border-radius: 0.5rem;
  background: var(--colour-surface);
}
CSS

overflow: auto adds scrollbars to the wrapper only when the table does not fit, so on a wide screen nothing changes. The max-height is there because of a side effect. Any overflow value other than visible makes the wrapper a scroll container in both directions, and the sticky header now sticks to the top of the wrapper, not the window. If the wrapper never scrolled vertically, the header would never stick. With a maximum height of 70 per cent of the viewport, the wrapper scrolls vertically once the list is long, and the header sticks inside it. The 30 per cent left over keeps the page scrollable around the table, so a user swiping on a phone is never trapped inside the box.

Sideways scrolling inside the box is acceptable here. WCAG 2.2 success criterion 1.4.10 Reflow asks for content to fit 320 CSS pixels without scrolling in two directions, but exempts content such as data tables that needs a two-dimensional layout to make sense, and the page around the table still reflows.

Check it worked

At 360 pixels wide, the heading "Front desk" stays still and fits the screen, and only the box with the table in it scrolls sideways. With a short window, scroll inside the box: the grey header row stays at the top of the box. Scroll the page instead, by dragging outside the box, and the box moves as a whole.

Step 5 · Make the scroll area focusable and labelled

A mouse or touch user can scroll the box. A keyboard user can only scroll what has focus, and a div cannot take focus by default. The three attributes on the wrapper deal with that:

  • tabindex="0" puts the wrapper in the Tab order. Once it has focus, the arrow keys scroll it. Firefox, and Chrome and Edge from version 130, make scroll areas with no focusable content focusable on their own; Safari does not, so keep the attribute.
  • role="region" turns the wrapper into a landmark, and aria-labelledby="appointments-caption" gives it the caption's text as its name. A screen reader user who tabs to it hears something like "Appointments, Tuesday 9 December, region" instead of focus landing on an unnamed box. A region without a name is not exposed as a landmark at all, so the label is not optional.

Pointing at the caption, rather than repeating the text in an aria-label, means the name changes when the caption changes. A focusable element also needs a visible focus indicator, so add one:

Bash
cd ~/larkfield-table-demo
cat >> table.css <<'CSS'

.table-scroll:focus-visible {
  outline: 3px solid var(--colour-text);
  outline-offset: 2px;
}
CSS

The rule for tabindex on a scroll wrapper: add it when the scroll area holds nothing focusable, as here, where every cell is plain text. If every row has a link or button, pressing Tab already scrolls the box to each one, so the wrapper can drop tabindex. The cost of keeping it is small but real: on a wide desktop screen, where nothing overflows, the wrapper is still one extra tab stop.

Check it worked

At 360 pixels wide, click in the browser's address bar and press Tab. A dark ring appears around the table box. Press the right arrow key a few times and the table scrolls sideways. If you have a screen reader running (VoiceOver with Cmd+F5 on macOS, Narrator with Ctrl+Windows+Enter on Windows, or TalkBack on Android), it announces the region with the caption's text when focus arrives.

Step 6 · Pin the time column on a phone

Scroll sideways on a phone and the times disappear, so a status of "Arrived" has no row label in sight. Make the row headers sticky on the left, and give the top-left header cell both directions:

Bash
cd ~/larkfield-table-demo
cat >> table.css <<'CSS'

.appointments tbody th,
.appointments thead th:first-child {
  position: sticky;
  inset-inline-start: 0;
  border-inline-end: 1px solid var(--colour-line);
}

.appointments tbody th { z-index: 1; }
.appointments thead th:first-child { z-index: 3; }
CSS

inset-inline-start is the logical form of left: in a left-to-right page it is left, and in a right-to-left page it becomes right, so the column pins to the side where reading starts. The stacking order is the part people get wrong. Body cells are at the bottom, the pinned time cells at 1 slide over them sideways, the header cells at 2 cover the time cells when scrolling down, and the corner cell at 3 sits over everything, because it is the one cell that is stuck in both directions. The line on the pinned column's edge shows where the frozen part ends and doubles as a hint that more columns are hidden.

This is a few lines of CSS and no JavaScript library, which matters for staff on a low-end Android phone on prepaid data: there is nothing extra to download or run, and sticky positioning and scrolling are handled by the browser itself.

Check it worked

At 360 pixels wide, scroll the box to the right. The Time column stays on the left with a thin line along its edge, and the other columns slide under it. Scroll down as well: the "Time" header cell stays in the top-left corner over both the header row and the time column, and no text shows through any sticky cell.

Step 7 · Check it with a Playwright script

A script that checks the table at two widths keeps working after someone edits the CSS. Install Playwright in the demo folder, with the Chromium browser it drives. On Linux, --with-deps also installs the system libraries Chromium needs and asks for your password to do it:

Bash
cd ~/larkfield-table-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

The script checks the semantics through the accessibility tree, the same way assistive technology sees the table, then measures the layout at 1,000 by 500 pixels and at 360 by 700 pixels:

Bash
cd ~/larkfield-table-demo
cat > check-table.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';

const url = new URL('./index.html', import.meta.url).href;
const browser = await chromium.launch();
const open = async (width, height) => {
  const page = await browser.newPage({ viewport: { width, height } });
  await page.goto(url);
  return page;
};
const box = (page, sel) => page.$eval(sel, (el) => {
  const r = el.getBoundingClientRect();
  return { x: r.x, y: r.y, w: r.width, h: r.height };
});
const topElementIs = (page, sel) => page.$eval(sel, (el) => {
  const r = el.getBoundingClientRect();
  return document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2) === el;
});
const caption = 'Appointments, Tuesday 9 December';

// Semantics, as assistive technology sees them
let page = await open(1000, 500);
const table = page.getByRole('table', { name: caption });
assert.equal(await table.count(), 1, 'one table, named by its caption');
assert.equal(await table.getByRole('columnheader').count(), 7, 'seven column headers');
assert.equal(await table.getByRole('rowheader').count(), 12, 'twelve row headers');
assert.equal(await table.getByRole('row').count(), 13, 'header row plus twelve rows');
assert.equal(await page.getByRole('region', { name: caption }).count(), 1, 'scroll area is a named region');
console.log('semantics ok: caption, 7 column headers, 12 row headers, named region');

// Numbers
assert.equal(await page.$eval('.appointments td', (el) => getComputedStyle(el).fontVariantNumeric), 'tabular-nums', 'tabular figures');
assert.equal(await page.$eval('tbody td.num', (el) => getComputedStyle(el).textAlign), 'end', 'length cells aligned to the end');
assert.equal(await page.$eval('thead th.num', (el) => getComputedStyle(el).textAlign), 'end', 'length header aligned to the end');

// Desktop: no sideways scroll, header sticks inside the box
const wideOverflow = await page.$eval('.table-scroll', (el) => el.scrollWidth > el.clientWidth);
assert.equal(wideOverflow, false, 'no sideways scroll at 1000px');
const wrap = await box(page, '.table-scroll');
await page.$eval('.table-scroll', (el) => { el.scrollTop = 200; });
const head = await box(page, 'thead th:nth-child(3)');
assert.ok(Math.abs(head.y - wrap.y) <= 2, `header stuck to the top of the box (${head.y} vs ${wrap.y})`);
assert.ok(await topElementIs(page, 'thead th:nth-child(3)'), 'header painted over the rows');
console.log('desktop ok: header sticks after scrolling 200px');
await page.close();

// Phone: the box scrolls, the page does not
page = await open(360, 700);
const pageOverflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(pageOverflow, false, 'page does not scroll sideways at 360px');
const widths = await page.$eval('.table-scroll', (el) => [el.scrollWidth, el.clientWidth]);
assert.ok(widths[0] > widths[1], 'table scrolls sideways inside the box');

// Keyboard: Tab reaches the box, arrows scroll it
await page.keyboard.press('Tab');
assert.ok(await page.$eval('.table-scroll', (el) => el === document.activeElement), 'Tab focuses the scroll area');
assert.equal(await page.$eval('.table-scroll', (el) => getComputedStyle(el).outlineStyle), 'solid', 'focus ring shows');
for (let i = 0; i < 5; i++) await page.keyboard.press('ArrowRight');
// Keyboard scrolling can be animated, so wait for it to move
await page.waitForFunction(() => document.querySelector('.table-scroll').scrollLeft > 0, null, { timeout: 5000 })
  .catch(() => assert.fail('arrow keys scroll the table'));
await page.waitForTimeout(500);
const keyScroll = await page.$eval('.table-scroll', (el) => el.scrollLeft);
console.log(`phone ok: box ${widths[0]}px wide in ${widths[1]}px, arrow keys scrolled ${Math.round(keyScroll)}px`);

// Sticky time column and corner cell
await page.$eval('.table-scroll', (el) => { el.scrollLeft = 300; el.scrollTop = 150; });
const phoneWrap = await box(page, '.table-scroll');
const time = await box(page, 'tbody tr:nth-child(7) th');
const patient = await box(page, 'tbody tr:nth-child(7) td');
assert.ok(Math.abs(time.x - phoneWrap.x) <= 2, `time column pinned to the left (${time.x} vs ${phoneWrap.x})`);
assert.ok(patient.x < time.x + time.w, 'patient column slid under the time column');
assert.ok(await topElementIs(page, 'tbody tr:nth-child(7) th'), 'time cell painted over the row');
assert.ok(await topElementIs(page, 'thead th:first-child'), 'corner cell painted over everything');
const corner = await box(page, 'thead th:first-child');
assert.ok(Math.abs(corner.x - phoneWrap.x) <= 2 && Math.abs(corner.y - phoneWrap.y) <= 2, 'corner cell stuck in both directions');
console.log('phone ok: time column and corner cell stay put');
await browser.close();
JS
node check-table.mjs

Check it worked

The script prints four lines starting semantics ok, desktop ok, phone ok and phone ok again, the first of the phone lines with the box's scroll width and how far the arrow keys moved it, and exits without an error. To see a failure, comment out the position: sticky rule for the row headers in table.css, run node check-table.mjs again, and it stops with time column pinned to the left. Put the rule back afterwards.

Step 8 · Clean up

Remove the demo folder, including the Playwright packages installed into it:

Bash
cd ~
rm -rf ~/larkfield-table-demo

Playwright keeps the downloaded Chromium in a shared cache (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS). Delete that folder too if no other project uses Playwright.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.