Frontend development · Intermediate · 20 min
Build accessible tabs with ARIA
By Padding · Updated 18 Nov 2026
Modern browsers · WAI-ARIA 1.2 and the ARIA Authoring Practices tabs pattern · checked in Chromium with Playwright 1.65.1
You will build Upcoming and Past appointment tabs with tab roles, aria-selected, panels linked to their tabs, a roving tabindex and arrow-key movement, and a Playwright script that drives them by keyboard alone.
On this page
A row of tabs looks like a handful of buttons, but to a screen reader or a keyboard user it is one control with its own rules. The tabs are announced as a set ("tab, 1 of 2, selected"), the Tab key enters the set once and leaves it once, and the arrow keys move between tabs. HTML has no tab element, so you build that contract yourself from ARIA roles, two or three attributes and about thirty lines of JavaScript. Get one part wrong and the tabs either read as loose buttons or trap people in a row they cannot leave.
The example is the "Your appointments" screen of the Larkfield Clinic booking app, the fictional community clinic used across this library. A patient sees two tabs: Upcoming, holding their Nurse appointment on Tuesday 9 December at 10:30, and Past, holding the visits they have already had. This is the first composite widget in the frontend category: one control made of several focusable parts, where the keyboard model matters as much as the markup.
You write plain HTML, CSS and JavaScript with no framework and no build step, then a Playwright script that presses keys and checks what the accessibility tree reports.
Step 1 · Decide whether this needs tabs at all
Tabs are the right pattern when the views are siblings of the same thing, each one is short, and people switch between them often without wanting a new page. Upcoming and Past appointments fit: both are lists of the same patient's bookings, and a patient checks one, then glances at the other.
Plain links to separate pages are the better choice when any of these is true:
- Each view deserves its own address. If people bookmark it, share it, or expect the browser's Back button to return to it, give it a URL. Tabs change the page without changing history.
- A view is long or slow to load. Tabs promise an instant switch; a view that fetches a lot of data breaks that promise, and on prepaid mobile data a patient pays for content they may never open.
- The page must work without JavaScript. Tabs need script to show and hide panels. Links work everywhere.
- There are more than about five views, or their labels are long. A row of tabs that scrolls sideways on a 360-pixel phone hides options. That is a navigation problem, covered in Choose a navigation pattern for an app.
A common mistake runs the other way: a site's main navigation styled as tabs and marked up with role="tab". Navigation between pages is a list of links inside a nav element. Use the tab roles only when the panels live on the same page.
Check it worked
Write one sentence for your own screen that names the views and says why they are not separate pages. For Larkfield: "Upcoming and Past are two short lists of the same patient's bookings on one screen, and neither needs its own URL." If you cannot write that sentence without hedging, use links.
Step 2 · Write the markup
Make a folder and an HTML file. The structure is a tablist holding tab buttons, followed by one tabpanel per tab:
mkdir -p ~/larkfield-tabs-demo
cd ~/larkfield-tabs-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>Your appointments · Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="tabs.js" defer></script>
</head>
<body>
<main>
<h1>Your appointments</h1>
<div class="tabs" role="tablist" aria-label="Appointments">
<button type="button" role="tab" id="tab-upcoming"
aria-selected="true" aria-controls="panel-upcoming">Upcoming</button>
<button type="button" role="tab" id="tab-past"
aria-selected="false" aria-controls="panel-past" tabindex="-1">Past</button>
</div>
<section class="panel" role="tabpanel" id="panel-upcoming"
aria-labelledby="tab-upcoming" tabindex="0">
<p class="card"><strong>Nurse appointment</strong><br>
Tuesday 9 December, 10:30<br>
<a href="#change">Change or cancel</a></p>
</section>
<section class="panel" role="tabpanel" id="panel-past"
aria-labelledby="tab-past" tabindex="0" hidden>
<p class="card"><strong>GP appointment</strong><br>Tuesday 4 November, 09:20</p>
<p class="card"><strong>Vaccination</strong><br>Monday 13 October, 14:00</p>
</section>
<p><a href="#book">Book an appointment</a></p>
</main>
</body>
</html>
HTMLEach attribute has one job:
role="tablist"groups the tabs, andaria-label="Appointments"names the group, because there is no visible heading for the row itself.role="tab"on a realbuttonkeeps the button's built-in focus and Enter and Space handling, and changes what assistive technology announces.aria-selectedsays which tab is current. Exactly one tab istrue.aria-controlson each tab andaria-labelledbyon each panel link the two in both directions, so the panel is announced with the tab's name: "Past, tab panel".hiddenon the inactive panel removes it from view and from the accessibility tree.tabindex="-1"on the unselected tab andtabindex="0"on the panels belong to the keyboard model in the step after next.
The panels get tabindex="0" because their first content is plain text. Without it, a keyboard user pressing Tab from the tabs would jump straight to the Change or cancel link and skip the appointment details. If a panel starts with a link or a button, leave tabindex off it.
Check it worked
Open index.html in a browser (drag it into a window, or run open index.html on macOS or xdg-open index.html on Linux). You see the heading, two unstyled buttons and only the Nurse appointment. The Past list is not visible. Clicking Past does nothing yet.
Step 3 · Style the tabs so the selected one is obvious without colour
The selected tab needs more than a colour change: a thick bar under it and heavier text work for people who cannot tell the clinic's green from grey. Style it from aria-selected itself, so the visual state can never disagree with what a screen reader hears:
cd ~/larkfield-tabs-demo
cat > style.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5;
color: #1B1F24; background: #F6F7F8; }
main { max-width: 32rem; margin: 0 auto; padding: 1rem; }
h1 { font-size: 1.75rem; margin: 0 0 1rem; }
.tabs { display: flex; border-bottom: 1px solid #D5D9DF; }
[role="tab"] {
flex: 1;
min-height: 3rem;
padding: 0.5rem 1rem;
border: 0;
border-bottom: 3px solid transparent;
background: none;
font: inherit;
color: #5A6270;
cursor: pointer;
}
[role="tab"][aria-selected="true"] {
color: #0F5E5A;
font-weight: 700;
border-bottom-color: #0F5E5A;
}
[role="tab"]:focus-visible,
.panel:focus-visible {
outline: 3px solid #0F5E5A;
outline-offset: 2px;
}
.panel { padding: 1rem 0; }
.card { background: #FFFFFF; border: 1px solid #D5D9DF; border-radius: 0.5rem;
padding: 1rem; margin: 0 0 0.75rem; }
a { color: #0F5E5A; }
CSSThe tabs share the width equally with flex: 1, and each is at least 3rem (48 pixels) tall, a comfortable target for a thumb on a small Android phone. The transparent bottom border on every tab keeps the text from jumping by 3 pixels when the selection moves. :focus-visible draws a ring for keyboard users without showing one after every mouse click.
Check it worked
Reload. Upcoming is bold, green and underlined by a thick bar; Past is grey and normal weight. Press Tab once: a green ring appears round Upcoming. Turn your screen to greyscale (or squint) and the selected tab is still clear from the bar and the weight.
Step 4 · Switch panels on click
All selection goes through one function. It updates aria-selected, the roving tabindex and each panel's hidden attribute together, so they cannot drift apart:
cd ~/larkfield-tabs-demo
cat > tabs.js <<'JS'
const tablist = document.querySelector('[role="tablist"]');
const tabs = [...tablist.querySelectorAll('[role="tab"]')];
function selectTab(tab) {
for (const t of tabs) {
const selected = t === tab;
t.setAttribute('aria-selected', String(selected));
t.tabIndex = selected ? 0 : -1;
document.getElementById(t.getAttribute('aria-controls')).hidden = !selected;
}
tab.focus();
}
tablist.addEventListener('click', (event) => {
const tab = event.target.closest('[role="tab"]');
if (tab) selectTab(tab);
});
JSThe click handler sits on the tablist, not on each tab, so a tab added later works without new wiring. selectTab also calls focus(), because Safari on macOS does not focus a button when you click it, and the next step relies on focus being on the selected tab.
Check it worked
Reload and click Past. The GP appointment and the Vaccination appear, the Nurse appointment disappears, and the bar moves under Past. In your browser's developer tools (F12, Elements panel), the Past button now shows aria-selected="true" and no tabindex="-1", and the Upcoming panel has gained hidden.
Step 5 · Add arrow keys and a roving tabindex
Here is the keyboard contract from the ARIA Authoring Practices tabs pattern. Only the selected tab is in the Tab order (tabindex="0"); the others have tabindex="-1", so they can take focus from script but the Tab key skips them. That is the roving tabindex: the single Tab stop moves with the selection. Inside the row, the arrow keys move between tabs, Home and End jump to the first and last, and focus wraps round at the ends.
Add the key handler to the end of tabs.js:
cd ~/larkfield-tabs-demo
cat >> tabs.js <<'JS'
tablist.addEventListener('keydown', (event) => {
const index = tabs.indexOf(document.activeElement);
if (index === -1) return;
const rtl = getComputedStyle(tablist).direction === 'rtl';
const nextKey = rtl ? 'ArrowLeft' : 'ArrowRight';
const prevKey = rtl ? 'ArrowRight' : 'ArrowLeft';
let target;
if (event.key === nextKey) target = tabs[(index + 1) % tabs.length];
else if (event.key === prevKey) target = tabs[(index - 1 + tabs.length) % tabs.length];
else if (event.key === 'Home') target = tabs[0];
else if (event.key === 'End') target = tabs[tabs.length - 1];
else return;
event.preventDefault();
selectTab(target);
});
JSAny other key returns early without preventDefault(), so Tab, Enter and screen reader shortcuts keep working. preventDefault() on the keys you do handle stops the arrows and Home and End from scrolling the page as well.
The rtl check swaps the arrows when the page is right to left. If Larkfield ships the app in Arabic, which many patients across North Africa read, the first tab sits on the right, and the arrow pointing left must move to the next tab.
This version uses automatic activation: moving to a tab shows its panel straight away. That suits panels already in the page. If a panel had to download its content, use manual activation instead: arrows move focus only, and Enter or Space selects. Otherwise a keyboard user pressing the arrow key to reach the third tab fetches the second on the way, which costs time and data.
Check it worked
Reload, press Tab once to reach Upcoming, then press the Right arrow. Focus and selection move to Past and its list shows. Press Right again: it wraps back to Upcoming. Press Tab: focus leaves the row and lands on the panel (a ring round the Nurse appointment area), not on the other tab. Press Shift+Tab: focus returns to the selected tab, not the first one.
Step 6 · Write a keyboard test
The keyboard contract is easy to break in a later edit, for example by removing the tabindex="-1" or renaming an id so aria-controls points nowhere. A Playwright script can press the same keys you just pressed and check what the browser's accessibility tree reports. Install Playwright and its Chromium in the demo folder:
cd ~/larkfield-tabs-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumOn Linux, --with-deps installs the system libraries Chromium needs and may ask for your password. Then write the test. getByRole finds elements by their accessible role, name and state, the same information a screen reader uses, so the test fails if the ARIA is wrong even when the page looks right:
cd ~/larkfield-tabs-demo
cat > check-tabs.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 page = await browser.newPage({ viewport: { width: 360, height: 740 } });
const focused = () => page.evaluate(() => document.activeElement.id);
const selectedTab = () => page.getByRole('tab', { selected: true }).textContent();
const panelShown = (name) => page.getByRole('tabpanel', { name }).isVisible();
const tabIndexes = () => page.$$eval('[role="tab"]', (ts) => ts.map((t) => t.tabIndex).join(','));
await page.goto(url);
assert.equal(await page.getByRole('tablist', { name: 'Appointments' }).count(), 1, 'named tablist');
assert.equal(await page.getByRole('tab').count(), 2, 'two tabs');
const linked = await page.$$eval('[role="tab"]', (ts) => ts.every((t) => {
const p = document.getElementById(t.getAttribute('aria-controls'));
return p && p.getAttribute('role') === 'tabpanel' && p.getAttribute('aria-labelledby') === t.id;
}));
assert.ok(linked, 'each tab controls a panel labelled by it');
console.log('structure: tablist, tabs and linked panels ok');
await page.keyboard.press('Tab');
assert.equal(await focused(), 'tab-upcoming', 'first Tab reaches the selected tab');
assert.equal(await selectedTab(), 'Upcoming');
assert.ok(await panelShown('Upcoming'), 'Upcoming panel shown');
assert.equal(await panelShown('Past'), false, 'Past panel hidden');
assert.equal(await tabIndexes(), '0,-1', 'only the selected tab is in the Tab order');
console.log('start: Upcoming selected, one Tab stop ok');
await page.keyboard.press('ArrowRight');
assert.equal(await focused(), 'tab-past', 'Right arrow moves focus');
assert.equal(await selectedTab(), 'Past', 'Right arrow selects');
assert.ok(await panelShown('Past'), 'Past panel shown');
assert.equal(await panelShown('Upcoming'), false, 'Upcoming panel hidden');
assert.equal(await tabIndexes(), '-1,0', 'Tab stop moved with the selection');
assert.match(await page.getByRole('tabpanel', { name: 'Past' }).textContent(), /Vaccination/);
console.log('arrows: Right selects Past ok');
await page.keyboard.press('ArrowRight');
assert.equal(await focused(), 'tab-upcoming', 'Right arrow wraps to the first tab');
await page.keyboard.press('ArrowLeft');
assert.equal(await focused(), 'tab-past', 'Left arrow wraps to the last tab');
await page.keyboard.press('Home');
assert.equal(await selectedTab(), 'Upcoming', 'Home selects the first tab');
await page.keyboard.press('End');
assert.equal(await selectedTab(), 'Past', 'End selects the last tab');
console.log('wrap: arrows wrap, Home and End ok');
await page.keyboard.press('Tab');
assert.equal(await focused(), 'panel-past', 'Tab leaves the row for the panel');
await page.keyboard.press('Shift+Tab');
assert.equal(await focused(), 'tab-past', 'Shift+Tab returns to the selected tab');
console.log('exit: Tab to panel, Shift+Tab back ok');
await page.getByRole('tab', { name: 'Upcoming' }).click();
assert.equal(await selectedTab(), 'Upcoming', 'click selects');
assert.ok(await panelShown('Upcoming'));
assert.equal(await focused(), 'tab-upcoming', 'click focuses the tab');
const bar = await page.$eval('#tab-upcoming', (t) => getComputedStyle(t).borderBottomColor);
assert.equal(bar, 'rgb(15, 94, 90)', 'selected tab has the accent bar');
console.log('click: Upcoming selected, accent bar ok');
await page.evaluate(() => { document.documentElement.dir = 'rtl'; });
await page.focus('#tab-upcoming');
await page.keyboard.press('ArrowLeft');
assert.equal(await selectedTab(), 'Past', 'Left arrow moves forward in right-to-left');
console.log('rtl: arrows follow reading direction ok');
await browser.close();
console.log('All tab checks passed');
JSCheck it worked
Run it:
cd ~/larkfield-tabs-demo
node check-tabs.mjsIt prints one line per behaviour and ends with All tab checks passed:
structure: tablist, tabs and linked panels ok
start: Upcoming selected, one Tab stop ok
arrows: Right selects Past ok
wrap: arrows wrap, Home and End ok
exit: Tab to panel, Shift+Tab back ok
click: Upcoming selected, accent bar ok
rtl: arrows follow reading direction ok
All tab checks passedTo watch it catch a regression, delete tabindex="-1" from the Past button in index.html and run node check-tabs.mjs again. It stops at "only the selected tab is in the Tab order". Put the attribute back afterwards.
Step 7 · Clean up
When you have finished, remove the Chromium download that Playwright added, then the folder. Skip the first command if you use Playwright in other projects, because it removes the browsers this Playwright version installed for all of them:
cd ~/larkfield-tabs-demo
npx playwright uninstall
cd ~
rm -rf ~/larkfield-tabs-demoCheck it worked
ls ~/larkfield-tabs-demo reports that there is no such file or directory.
Next steps
- Whether a screen needs tabs, a bottom bar or separate pages is a design decision, worked through in Choose a navigation pattern for an app.
- The
Change or cancellink leads to a confirmation built in Build an accessible modal with the dialog element, which has its own focus rules. - Radio buttons also move with the arrow keys and keep one Tab stop, without any ARIA; see Build a time slot picker with radio buttons.
- To make the focus ring hold up on any background and in forced colours mode, follow Style keyboard focus with :focus-visible.
Part of these paths
Related tutorials
- Build an accessible modal with the dialog elementYou will build the Larkfield Clinic "Cancel this appointment?" confirmation with the native dialog element and showModal(), with focus that moves in and comes back, Escape and backdrop dismissal, an inert page behind, a safe default button, a bottom-sheet layout on phones and a Playwright keyboard test that proves all of it.
- Choose a navigation pattern for an appYou will have compared a bottom tab bar, a top app bar with a drawer and a hub screen for the Larkfield Clinic app, written down why one wins, and drawn it on four screens with active, inactive and badge states.
- Style keyboard focus with :focus-visibleYou will remove an outline reset that hides keyboard focus, add a two-colour focus ring with :focus-visible that stays visible on white, tinted and accent backgrounds, keep it clear of a sticky header with scroll-margin, check it in forced colours mode and prove it all with a Playwright keyboard test.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials