Frontend development · Intermediate · 20 min
Build an accessible modal with the dialog element
By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard dialog element · checked in Chromium with Playwright 1.65.1
You 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.
On this page
A hand-made modal is a stack of jobs: put a box on top of everything, dim the page, stop clicks and the Tab key reaching the page behind, move focus in, close on Escape, and put focus back where it was. Libraries exist because each of those is easy to get slightly wrong. The HTML dialog element, opened with showModal(), does all of them in the browser. Your code decides what the dialog says and what happens with the answer.
The example is the confirmation from the Larkfield Clinic booking app, the fictional community clinic used across this library. A patient has a Nurse appointment on Tuesday 9 December at 10:30 and wants to cancel it. Once cancelled, the slot goes back to other patients, so the app asks first: Cancel this appointment?, with Keep appointment and Cancel appointment stacked full width. The design reasons for a modal here, rather than a sheet or a new screen, are in Choose between a modal, a bottom sheet and a new screen. This tutorial builds it.
You write plain HTML, CSS and about twenty lines of JavaScript, with no framework and no build step. Nothing extra is downloaded to show the dialog, which matters for patients on prepaid data and low-end Android phones. The last steps add a Playwright script that drives the dialog with the keyboard only.
Step 1 · Write the page and the dialog markup
Make a folder for the demo. The stylesheet starts with the Larkfield colour variables you need (the same names and values as the high-fidelity design), then the bookings page itself:
mkdir -p ~/larkfield-dialog-demo
cd ~/larkfield-dialog-demo
cat > styles.css <<'CSS'
:root {
--colour-text: #1b1f24;
--colour-text-muted: #5a6270;
--colour-surface: #ffffff;
--colour-canvas: #f6f7f8;
--colour-border: #7d8592;
--colour-accent: #0f5e5a;
--colour-on-accent: #ffffff;
--colour-danger: #b42318;
}
* { 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; }
h1 { font-size: 1.75rem; margin: 0 0 1rem; }
.card { background: var(--colour-surface); border-radius: 12px; padding: 1rem; margin-bottom: 1rem; max-width: 26rem; }
.card h2 { font-size: 1.125rem; margin: 0; }
.card p { margin: 0 0 1rem; color: var(--colour-text-muted); }
button { min-height: 48px; padding: 0 1rem; border-radius: 8px; font: inherit; font-weight: 600; cursor: pointer; }
.button-secondary { background: var(--colour-surface); color: var(--colour-text); border: 1px solid var(--colour-border); }
.button-danger { background: var(--colour-danger); color: var(--colour-on-accent); border: 1px solid var(--colour-danger); }
button:focus-visible { outline: 3px solid var(--colour-accent); outline-offset: 2px; }
CSSNow the page. The booking card has the button that opens the dialog. In the full app it sits behind Change or cancel; here it opens the confirmation directly. The dialog is in the markup from the start, closed:
cd ~/larkfield-dialog-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 bookings · Larkfield Clinic</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="dialog.css">
<script src="app.js" defer></script>
</head>
<body>
<main>
<h1>Your bookings</h1>
<article class="card" id="booking">
<h2>Nurse appointment</h2>
<p>Tuesday 9 December, 10:30</p>
<button type="button" class="button-secondary" id="open-cancel">Cancel this appointment</button>
</article>
<p id="status" role="status" tabindex="-1"></p>
<a href="#book" id="book-another">Book another appointment</a>
</main>
<dialog id="cancel-dialog" class="sheet" aria-labelledby="cancel-title" aria-describedby="cancel-detail">
<div class="sheet-body">
<h2 id="cancel-title">Cancel this appointment?</h2>
<div id="cancel-detail">
<p>Nurse appointment, Tuesday 9 December, 10:30.</p>
<p class="muted">The time goes back to other patients straight away.</p>
</div>
<form method="dialog" class="sheet-actions">
<button value="keep" class="button-secondary" autofocus>Keep appointment</button>
<button value="cancel" class="button-danger">Cancel appointment</button>
</form>
</div>
</dialog>
</body>
</html>
HTMLFour details in the dialog markup do accessibility work:
dialogalready has thedialogrole, so you add noroleattribute.aria-labelledbygives it the heading as its name, andaria-describedbypoints at the two lines of detail, so a screen reader announces the question and the appointment when the dialog opens.form method="dialog"makes each button close the dialog when pressed and store itsvaluein the dialog'sreturnValue. You do not write a click handler per button.Keep appointmentcomes first in the source and hasautofocus. When the dialog opens, focus goes to it, so Enter or Space on arrival keeps the booking. The destructive button is never the default.- The padding lives on the inner
div, not ondialogitself. That matters in a later step, when a click on the dimmed area must be told apart from a click inside the box.
Check it worked
Open index.html in your browser (drag the file into a window, or run open index.html on macOS or xdg-open index.html on Linux). You see the heading Your bookings and one card for the Nurse appointment with a Cancel this appointment button. The dialog is not visible: a closed dialog is not rendered at all. The browser console may report that dialog.css and app.js are missing, which the next two steps fix.
Step 2 · Open it with showModal()
A dialog can be opened two ways. show() opens it as a plain box in the page flow: nothing is blocked. showModal() opens it as a modal, which does four things at once. It puts the dialog in the top layer, above every other element whatever its z-index. It makes everything outside the dialog inert, so it cannot be clicked, focused or found by a screen reader's browse mode. It moves focus into the dialog. And it makes Escape close the dialog.
Write the script with one listener on the card's button:
cd ~/larkfield-dialog-demo
cat > app.js <<'JS'
const dialog = document.querySelector('#cancel-dialog');
const openButton = document.querySelector('#open-cancel');
openButton.addEventListener('click', () => {
dialog.returnValue = '';
dialog.showModal();
});
JSResetting returnValue first matters. It keeps the value from the last time the dialog closed, and Escape does not change it. Without the reset, a patient who pressed Keep appointment once and Escape the next time would get the old value, and a patient who had chosen Cancel appointment before would have that answer repeated.
Also create an empty dialog.css for now, so the page loads cleanly:
cd ~/larkfield-dialog-demo
: > dialog.cssCheck it worked
Reload the page and use only the keyboard. Press Tab once: the focus ring is on Cancel this appointment. Press Enter: the dialog appears over a lightly dimmed page and the ring is on Keep appointment. Press Tab: the ring moves to Cancel appointment. Try to click Book another appointment with the mouse: nothing happens. Press Escape: the dialog closes and the ring is back on Cancel this appointment. The browser returned focus to the element that had it before the dialog opened; you wrote no code for that.
Step 3 · Style the dialog and its backdrop
The browser's default dialog is a centred box with a black border. Give it the Larkfield look and darken the page behind it. The ::backdrop pseudo-element is the layer between the dialog and the page; it only exists for modal dialogs:
cd ~/larkfield-dialog-demo
cat > dialog.css <<'CSS'
.sheet {
width: min(26rem, 100% - 2rem);
padding: 0;
border: none;
border-radius: 12px;
background: var(--colour-surface);
color: var(--colour-text);
box-shadow: 0 8px 32px rgb(27 31 36 / 0.25);
}
.sheet::backdrop {
background: rgb(27 31 36 / 0.6);
}
.sheet-body {
padding: 1.5rem;
}
.sheet h2 {
font-size: 1.375rem;
line-height: 1.3;
margin: 0 0 0.5rem;
}
.sheet p {
margin: 0 0 0.5rem;
}
.sheet .muted {
color: var(--colour-text-muted);
}
.sheet-actions {
display: grid;
gap: 0.75rem;
margin-top: 1.5rem;
}
.sheet-actions button {
width: 100%;
}
html:has(dialog[open]) {
overflow: hidden;
}
CSSThe buttons are stacked and full width. Two four-word labels do not fit side by side at a readable size on a 360 pixel phone, and a translated label, in Hausa, Yoruba or French for example, is often longer than the English. The last rule stops the page behind from scrolling while the dialog is open. Inert content cannot be clicked, but without this rule a long page still scrolls under the patient's thumb.
Check it worked
Reload and open the dialog. It is a white card with rounded corners and no border, centred on a dark overlay. The two buttons fill the card's width, Keep appointment with a grey border on top and a red Cancel appointment below it. Tab to each button: the teal focus ring shows clearly on both.
Step 4 · Act on the answer
The dialog closes itself whichever way the patient leaves it. Your code only needs to look at returnValue when it has closed. The close event fires for every route: either button, Escape, or a call to dialog.close(). Add the handler, and a rule for clicks on the dimmed area:
cd ~/larkfield-dialog-demo
cat >> app.js <<'JS'
const booking = document.querySelector('#booking');
const statusLine = document.querySelector('#status');
// A click whose target is the dialog itself landed on the backdrop:
// all the visible content is inside .sheet-body.
dialog.addEventListener('click', (event) => {
if (event.target === dialog) dialog.close('keep');
});
dialog.addEventListener('close', () => {
if (dialog.returnValue !== 'cancel') return;
booking.hidden = true;
statusLine.textContent = 'Your nurse appointment on Tuesday 9 December at 10:30 is cancelled.';
statusLine.focus();
});
JSThree things to notice:
- Only the exact value
cancelcancels. Escape leavesreturnValueempty,Keep appointmentsetskeep, and the backdrop click passeskeeptoclose(). Every way out that is not a deliberate press of the red button keeps the booking. - After a cancellation, the button that opened the dialog is hidden with the card. The browser would return focus to it, find nothing to focus, and leave the keyboard user at the top of the page. So the handler moves focus to the status line, which has
tabindex="-1"to make it focusable by script and not by Tab. Itsstatusrole also makes screen readers announce the message. - Newer browsers also support a
closedby="any"attribute ondialog, which gives backdrop dismissal without the click handler. Check its current support on MDN before you rely on it; the handler above works everywhereshowModal()does.
In Chrome on Android, the system back gesture closes a modal dialog the same way Escape does, so it also keeps the appointment.
Check it worked
Reload. Open the dialog and click the dark area outside the card: it closes and the booking is still there. Open it, press Escape: the same. Open it, press Tab, then Enter on Cancel appointment: the card disappears, the line Your nurse appointment on Tuesday 9 December at 10:30 is cancelled. appears, and the next Tab goes to Book another appointment, not back to the top of the page. Reload to bring the card back.
Step 5 · Turn it into a bottom sheet on phones
On a phone, a box in the middle of the screen puts both buttons in the hardest place for a thumb to reach. Below 40rem, anchor the dialog to the bottom edge, full width, with only the top corners rounded. The browser's own dialog styles centre it with margin: auto and limit its width; overriding the margin and the maximum width is enough:
cd ~/larkfield-dialog-demo
cat >> dialog.css <<'CSS'
@media (max-width: 40rem) {
.sheet {
width: 100%;
max-width: 100%;
margin: auto 0 0;
border-radius: 16px 16px 0 0;
}
.sheet-body {
padding-bottom: calc(1.5rem + env(safe-area-inset-bottom));
}
}
CSSmargin: auto 0 0 keeps the automatic top margin, which pushes the box down, and sets the side and bottom margins to zero. A modal dialog is fixed to the viewport, so the bottom is the bottom of the screen, not of the page. env(safe-area-inset-bottom) adds room above the home indicator on phones that have one and is zero elsewhere.
The behaviour does not change: it is the same element with the same focus, Escape and inert rules. Only its position does.
Check it worked
Open your browser's responsive or device mode (in Chrome and Edge, F12 then the device toolbar button; in Firefox, Ctrl+Shift+M or Cmd+Option+M on macOS) and pick a width of 360 pixels. Open the dialog: it rises from the bottom edge, touches both sides of the screen, and has rounded top corners only. Widen past 640 pixels and open it again: it is the centred card from before.
Step 6 · Write a keyboard test
The behaviour you checked by hand is easy to break later, for example by someone replacing the form with click handlers or adding a second button above Keep appointment. A Playwright script can drive the page with the keyboard and fail when any of it changes. Install Playwright and its Chromium in the demo folder:
cd ~/larkfield-dialog-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. Each block is one claim from this tutorial:
cd ~/larkfield-dialog-demo
cat > check-dialog.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: 1000, height: 700 } });
const focused = () => page.evaluate(() => document.activeElement.id || document.activeElement.textContent.trim());
const waitClosed = () => page.waitForFunction(() => !document.querySelector('#cancel-dialog').open);
await page.goto(url);
await page.keyboard.press('Tab');
assert.equal(await focused(), 'open-cancel', 'first Tab reaches the card button');
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => document.querySelector('#cancel-dialog').matches(':modal')), true, 'opens as a modal');
assert.equal(await focused(), 'Keep appointment', 'focus starts on the safe button');
console.log('open: modal, focus on Keep appointment ok');
const reachedOutside = await page.evaluate(() => {
const link = document.querySelector('#book-another');
link.focus();
const button = document.querySelector('#open-cancel').getBoundingClientRect();
const hit = document.elementFromPoint(button.x + 5, button.y + 5);
return document.activeElement === link || hit.id === 'open-cancel';
});
assert.equal(reachedOutside, false, 'page behind cannot be focused or clicked');
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).overflow), 'hidden', 'page scroll locked');
await page.keyboard.press('Tab');
assert.equal(await focused(), 'Cancel appointment', 'Tab moves to the second button');
await page.keyboard.press('Shift+Tab');
assert.equal(await focused(), 'Keep appointment', 'Shift+Tab moves back');
console.log('inert: page behind unreachable, scroll locked ok');
await page.keyboard.press('Escape');
await waitClosed();
assert.equal(await focused(), 'open-cancel', 'focus returns to the opener');
assert.equal(await page.isVisible('#booking'), true, 'Escape keeps the booking');
console.log('escape: closed, focus returned, booking kept ok');
await page.keyboard.press('Enter');
await page.mouse.click(10, 10);
await waitClosed();
assert.equal(await page.isVisible('#booking'), true, 'backdrop click keeps the booking');
console.log('backdrop: closed, booking kept ok');
await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
await waitClosed();
assert.equal(await page.isVisible('#booking'), true, 'Enter on arrival keeps the booking');
console.log('default: Enter on arrival keeps the booking ok');
const box = await page.locator('#cancel-dialog').evaluate((d) => { d.showModal(); const r = d.getBoundingClientRect(); d.close(); return r.toJSON(); });
assert.ok(box.x > 0 && box.bottom < 700, 'centred card on a wide screen');
await page.focus('#open-cancel');
await page.keyboard.press('Enter');
await page.keyboard.press('Tab');
await page.keyboard.press('Enter');
await waitClosed();
assert.equal(await page.isVisible('#booking'), false, 'booking removed');
assert.equal(await focused(), 'status', 'focus moves to the status line');
assert.match(await page.textContent('#status'), /is cancelled/);
console.log('cancel: booking removed, focus on status ok');
const phone = await browser.newPage({ viewport: { width: 360, height: 740 } });
await phone.goto(url);
await phone.click('#open-cancel');
const sheet = await phone.locator('#cancel-dialog').evaluate((d) => d.getBoundingClientRect().toJSON());
assert.equal(Math.round(sheet.width), 360, 'sheet is full width');
assert.equal(Math.round(sheet.bottom), 740, 'sheet sits on the bottom edge');
console.log('phone: bottom sheet, full width ok');
await browser.close();
console.log('All dialog checks passed');
JSCheck it worked
Run it:
cd ~/larkfield-dialog-demo
node check-dialog.mjsIt prints one line per behaviour and ends with All dialog checks passed:
open: modal, focus on Keep appointment ok
inert: page behind unreachable, scroll locked ok
escape: closed, focus returned, booking kept ok
backdrop: closed, booking kept ok
default: Enter on arrival keeps the booking ok
cancel: booking removed, focus on status ok
phone: bottom sheet, full width ok
All dialog checks passedTo see it catch a regression, swap the two buttons in index.html so Cancel appointment comes first and remove autofocus, then run node check-dialog.mjs again. It stops at "focus starts on the safe button". Put the markup 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-dialog-demo
npx playwright uninstall
cd ~
rm -rf ~/larkfield-dialog-demoCheck it worked
ls ~/larkfield-dialog-demo reports that there is no such file or directory.
Next steps
- The design decision behind this dialog, and when a bottom sheet or a new screen fits better, is in Choose between a modal, a bottom sheet and a new screen.
- The buttons here are a cut-down version of the full Larkfield set, with hover, pressed, disabled and loading states, in Build the Larkfield button in HTML and CSS.
- To make the focus ring hold up on any background and in forced colours mode, follow Style keyboard focus with :focus-visible.
- Another pattern that opens and closes over the page, with its own focus rules, is Build a responsive navigation menu.
Part of these paths
Related tutorials
- Choose between a modal, a bottom sheet and a new screenYou will have decided, with written reasons, where four Larkfield Clinic tasks belong (inline, a modal dialog, a bottom sheet or a new screen), drawn each one, and turned the reasons into a three-question rule with a fallback that you can reuse.
- Build a responsive navigation menuYou will build the Larkfield Clinic site header, with links in a row on wide screens, a menu button on narrow ones that opens, closes on Escape and reports its state, a Book button that never hides, and a Playwright keyboard test that proves it works with and without JavaScript.
- Build the Larkfield button in HTML and CSSYou will build the Larkfield Clinic button as a real button element with primary, secondary and destructive variants drawn from colour tokens, hover, pressed, keyboard focus, disabled and loading states, a 48 pixel minimum height, and a Playwright script that checks every state's computed styles.
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