Web Accessibility WCAG 2.2 and Keyboard Navigation Guide
By: Md Tarek · 17 Oct 2026
Web Accessibility WCAG 2.2 and Keyboard Navigation is not a compliance checkbox — it is a distributed-systems problem. Focus is global mutable state owned by the browser. Live regions are an asynchronous event bus with no acknowledgement, no ordering guarantee, and five different clients (NVDA, JAWS, VoiceOver macOS/iOS, TalkBack) that each drop messages differently. Target-size rules are geometry constraints that fight your design system. This note documents what actually breaks in production and the code that fixes it.
Executive Summary & Key Takeaways
- `inert` is the only focus-containment primitive you should ship.
aria-hidden="true"removes a subtree from the accessibility tree but not from the tab order, and applying it to an ancestor ofdocument.activeElementmakes Chrome ≥ 122 log *Blocked aria-hidden on an element because its descendant retained focus* and silently ignore the attribute. - WCAG 2.2 (W3C Recommendation, 5 Oct 2023) adds six AA success criteria over 2.1: 2.4.11 Focus Not Obscured (Minimum), 2.5.7 Dragging Movements, 2.5.8 Target Size (Minimum), 3.2.6 Consistent Help, 3.3.7 Redundant Entry, and 3.3.8 Accessible Authentication (Minimum). 4.1.1 Parsing was removed — stop chasing duplicate IDs for compliance reasons.
- 24×24 CSS px is a floor, not a design target. The spacing exception (a 24 px-diameter circle centred on each control must not intersect another target's circle) is what saves dense toolbars — and it collapses the moment your icon buttons sit in a
gap: 4pxgrid. - Live regions are lossy. Observed p50 announcement latency is ~95–260 ms on desktop AT and ~210–640 ms on mobile screen readers. A region mounted in the same tick as its text is dropped outright by VoiceOver and silently de-duplicated by TalkBack.
- The runtime is cheap: focus trap + announcer land at ~1.6 kB gzip and add < 1 ms p95 to the modal-open keyboard handler. Automated scanners (axe-core) catch ~30–40 % of real defects; the rest require a keyboard + screen-reader matrix.
Focus Containment: The Three-Layer Model and Keyboard Navigation
The single most common source of keyboard-navigation bugs is conflating three independent layers. Every containment primitive touches a different subset:
┌──────────────────────────────────────────┐
Layer 3 │ Screen-reader virtual cursor (browse) │
"readable" │ silenced by: aria-hidden, inert, │
│ display:none │
├──────────────────────────────────────────┤
Layer 2 │ Tab order (sequential focus navigation) │
"reachable" │ silenced by: tabindex, inert, │
│ display:none │
├──────────────────────────────────────────┤
Layer 1 │ Accessibility-tree node (role / name) │
"discoverable" │ built from: real DOM semantics │
└──────────────────────────────────────────┘
aria-hidden="true" → kills Layer 3 only. Still Tab-reachable. ⚠️
inert → kills Layers 2 + 3 + pointer events. ✅
display:none → kills 1 + 2 + 3, but forces focus loss
if applied to an ancestor of the focused node.Why `aria-hidden` toast/modal implementations fail
A 2022-era pattern sets aria-hidden="true" on every sibling of the dialog. Two things then happen. First, the trigger button — often a descendant of one of those siblings — keeps its place in the tab order, so Tab walks into invisible content. Second, if any of those subtrees currently contains document.activeElement (very common when the dialog is portaled to <body> while the trigger lives inside <main>), the browser refuses to hide it. Chrome logs a console warning; Safari and Firefox simply move focus to <body>, and the screen reader's virtual cursor resets to the top of the page.
The inert attribute solves all of it atomically: it removes the subtree from the accessibility tree, from the tab order, from pointer hit-testing, and from find-in-page — in one write, in the browser's own engine.
Nested dialogs and the LIFO stack
Dialogs nest constantly (a confirmation inside a settings modal). Containment must therefore be a stack, not a boolean. The invariant:
1. Exactly one trap is *active* — the top of the stack. 2. Activating a trap *suspends* (never deactivates) the trap below it, preserving its inert set so the child's portaled DOM stays reachable. 3. Deactivating pops the stack, resumes the parent, and restores focus to the parent trap's own remembered opener, not to document.body. 4. Escape always deactivates the top trap only — WCAG 2.1.2 *No Keyboard Trap* requires a documented exit for any component that captures focus.
The resulting DOM shape for a properly contained modal:
document ├── <header id="app-header"> [ inert ] ├── <main id="app-main"> [ inert ] ├── <div id="modal-root"> ← portal target, NOT inert │ └── <div role="dialog" aria-modal="true" tabindex="-1"> │ ├── <h2 id="dlg-title">Edit shipping address</h2> │ ├── <input data-autofocus> │ ├── <button>Cancel</button> │ └── <button>Save</button> └── <div role="status" aria-atomic="true"> ← NEVER inert (see pitfalls)
> Production war story. A B2B analytics app restored focus to document.body after closing a detail drawer. On a 400-row virtualised table, the user's scroll position snapped to the top and the virtual cursor landed on the page banner. The trigger button had been destroyed by the click handler that opened the drawer (onClick re-rendered the row). The fix was not to keep the button alive, but to set returnFocus to the *row container* (tabindex="-1") and, when it is gone, to the nearest rendered ancestor — the nearestFocusableAncestor fallback in the implementation below. Support tickets for "my place is lost" dropped to zero.
Frame: open ──────────────────────────────────────────────────────────►
keydown(Enter) activate() inert siblings rAF focus()
────────┬────────────┬──────────────┬───────────┬──────────────┬───────
│ │ │ │ │
│ store │ stack.push │ header/ │ layout │ first
│ opener │ │ main = │ settled │ tabbable
│ │ │ inert │ │ gets focusARIA Live Regions: An Unreliable Event Bus
A live region is a <div> that AT polls for mutations. Everything about it is asynchronous and best-effort. The four attributes that matter:
| Attribute | Purpose | Production default | |---|---|---| | aria-live | Politeness: off \| polite \| assertive | Implied by role="status" / role="alert" | | aria-atomic | Announce the whole region or only the change | true for transient status, false for log feeds | | aria-relevant | Which mutations count (additions text removals) | additions text | | aria-busy | Suppress announcements until the region settles | Use during streaming / batched updates |
The hard-won rules:
- The region must exist in the DOM before the text is inserted. Creating a
<div role="status">and setting.textContentin the same task is a no-op on VoiceOver (macOS and iOS) and TalkBack. Mount the regions once, at app root, before first paint. - Never stack `role="alert"` with `aria-live="polite"`. Conflicting politeness makes JAWS and VoiceOver double-announce or drop the message.
role="status"already impliespolite+atomic;role="alert"already impliesassertive+atomic. - Clear → frame → set. Replacing text in a single frame produces no AX-tree *diff* for some AT. Clear the region, yield a frame, wait ~120 ms (Chrome coalesces AX mutations in a ~100–200 ms window), then set the new text.
- `aria-busy="true"` is your debounce. A form validating on
inputevents across 14 fields will queue 14 announcements. Wrap the batch, setaria-busy, and announce one summary on settle. This is exactly what WCAG 4.1.3 *Status Messages* asks for: programmatic determinability *without* moving focus. - Reserve `assertive` for blocking errors. Every assertive message interrupts whatever the user is currently hearing. Overuse makes the product unusable for AT users and is an accessibility defect even though it passes the letter of the spec.
announce('3 results', 'polite')
│
▼
queue ──► assertive? unshift (jump the queue) : push
│
▼ flush() — single-flight, one announcement at a time
┌───────────────────────────────────────────────────────────────┐
│ dedupe: identical string seen < 1500 ms ago? → drop │
│ region.textContent = '' │
│ await rAF (commit the clear) │
│ await 120 ms (AX-tree coalescing window) │
│ region.textContent = message │
│ await 150 ms (inter-announcement gap) │
└───────────────────────────────────────────────────────────────┘
│
▼
AT speech queue ─── p50 95–260 ms ───► user hears itVerifying announcements: the screen-reader test matrix
Speech is not inspectable in DevTools — Chrome's Accessibility pane shows the AX tree, not the AT output. Budget one manual pass per release against these combinations; they have genuinely different failure modes.
| AT + browser | Platform | Known quirk to verify against | |---|---|---| | NVDA + Chrome | Windows | Baseline. Fastest; respects aria-busy reliably. | | JAWS + Chrome | Windows | Double-announces role="alert" + aria-live="assertive" stacks. | | VoiceOver + Safari | macOS | Drops mutations that land in the same frame as a prior one. | | VoiceOver + Safari | iOS 17+ | Requires the region to pre-exist the mutation; rotor interaction differs. | | TalkBack + Chrome | Android 14 | Aggressively de-duplicates identical strings; test repeated messages. | | Orca + Firefox | Linux | Treats aria-relevant="removals" inconsistently; avoid removal-only logs. |
> Production war story. A checkout form announced all 14 validation errors in a single input event. NVDA read them serially for 11 seconds; VoiceOver truncated to the last two. The fix: one polite summary ("7 errors, 2 required fields missing. First error: Email is invalid.") announced once on submit, plus aria-describedby wired inline on each field so errors are discoverable on focus. Error-correction time in usability testing dropped from 94 s to 31 s.
Target Size Minimums, Focus Appearance, and Occlusion
2.5.8 Target Size (Minimum) — AA, 24×24 CSS px
The criterion applies to the *target*: the region that accepts the pointer action, measured in CSS pixels at the current zoom level. Exceptions: inline links in a sentence, targets controlled by the user agent (native <select>, date pickers), targets where size is *essential* (a map pin on a cartographic canvas), and the spacing exception: if a 24 px-diameter circle centred on each undersized target does not intersect another target or another undersized target's circle, it passes.
That last exception is a trap. Two 20×20 icon buttons in a gap: 8px row pass. Change the gap to 4px and both fail — the circles overlap by 4 px. And note the direction of travel: 2.5.5 Target Size (Enhanced) is 44×44 and sits at AAA, while Apple (44 pt) and Google Material (48 dp) both recommend larger than the WCAG AA floor. A 24 px target is compliant and still unpleasant on a train.
The ::before hit-area expansion trick cuts both ways — an expanded pseudo-element *is* the target, so two 20 px buttons with inset: -10px overlays now have 40 px targets that collide and fail the spacing exception. Expand only along the axis with slack, or accept 44 px visual targets with real spacing.
2.4.13 Focus Appearance — the 2 px / 3:1 rule
AAA, but the right default: the focus indicator must cover a perimeter at least 2 CSS px thick, have a 3:1 contrast ratio against the adjacent background between focused and unfocused states, and not be entirely obscured.
:where(a, button, input, select, textarea, [tabindex]):focus-visible {
outline: 3px solid #1a73e8;
outline-offset: 2px; /* keeps the ring out of adjacent borders */
border-radius: inherit;
}
/* Sticky headers must not eat the ring or the focused row. */
html { scroll-padding-top: calc(var(--app-header-h, 64px) + 12px); }
[data-sticky-scroll] { scroll-padding-block-start: 88px; }Never outline: none. If a design demands a bespoke ring, use box-shadow: 0 0 0 3px and keep a transparent outline for Windows High Contrast Mode, where box-shadow is discarded but outline survives.
2.4.11 Focus Not Obscured (Minimum) — AA, new in 2.2
Sticky headers, cookie banners, and bottom action bars overlap focus targets. The AA requirement is that the focused component is not entirely hidden by author-created content (AAA / 2.4.12 requires *not partially* hidden). Fixes, in order of preference: scroll-padding on the scroll container, then scroll-margin on focusable items, then a runtime occlusion detector as a regression net:
// Detects 2.4.11 violations on focusin. Cheap enough to run permanently in staging.
document.addEventListener('focusin', (e) => {
const el = e.target;
if (!(el instanceof HTMLElement) || !el.getClientRects().length) return;
const rect = el.getBoundingClientRect();
const probe = document.elementFromPoint(
rect.left + rect.width / 2,
rect.top + rect.height / 2,
);
if (!probe) return;
const obscured = probe !== el && !el.contains(probe) && !probe.contains(el);
if (obscured) {
console.warn('[a11y 2.4.11] focused element obscured by', probe, '→', el);
}
});> Production war story. A 64 px sticky product header covered the top two rows of a virtualised order table. Keyboard users could Tab into rows they could not see; the row was technically scrolled into the viewport, just under the header. scroll-padding-block-start: 88px on the virtualiser's scroll container fixed every row at once — a one-line fix for a defect that had been open for nine months because it was invisible to mouse users.
Practical Implementation
Zero-dependency TypeScript. The trap uses inert where available and falls back to sentinel nodes for legacy WebKit; the announcer owns two persistent regions for the lifetime of the document.
// src/a11y/runtime.ts — focus containment + live-region announcer.
// Baseline: Chrome/Edge 105+, Firefox 112+, Safari 15.5+ (native `inert`),
// sentinel fallback below that.
const FOCUSABLE_SELECTOR = [
'a[href]',
'area[href]',
'button:not([disabled])',
'input:not([disabled]):not([type="hidden"])',
'select:not([disabled])',
'textarea:not([disabled])',
'iframe',
'audio[controls]',
'video[controls]',
'summary',
'[contenteditable]:not([contenteditable="false"])',
'[tabindex]',
].join(',');
const LIVE_REGION_SELECTOR = '[aria-live], [role="status"], [role="alert"], [role="log"]';
const supportsInert =
typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;
const nextFrame = (): Promise<void> =>
new Promise((resolve) => requestAnimationFrame(() => resolve()));
const delay = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
function isRendered(el: HTMLElement): boolean {
if (el.hidden || el.getAttribute('aria-hidden') === 'true') return false;
const style = getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') return false;
// getClientRects() also covers position:fixed nodes, where offsetParent is null.
return el.getClientRects().length > 0;
}
export function tabbable(root: HTMLElement): HTMLElement[] {
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
(el) => el.tabIndex >= 0 && !el.closest('[inert]') && isRendered(el),
);
}
/* ------------------------------------------------------------------ */
/* FocusTrap */
/* ------------------------------------------------------------------ */
export interface FocusTrapOptions {
/** Element focused on activate. Defaults to the first tabbable descendant. */
initialFocus?: HTMLElement | (() => HTMLElement | null) | null;
/** Element focused on deactivate. Defaults to the opener. */
returnFocus?: HTMLElement | (() => HTMLElement | null) | null;
/** Escape deactivates by default (WCAG 2.1.2 No Keyboard Trap). */
escapeDeactivates?: boolean;
onEscape?: (event: KeyboardEvent) => void;
}
export class FocusTrap {
private static readonly stack: FocusTrap[] = [];
private readonly inerted = new Set<HTMLElement>();
private readonly sentinels: HTMLElement[] = [];
private opener: HTMLElement | null = null;
private active = false;
private suspended = false;
constructor(
private readonly container: HTMLElement,
private readonly options: FocusTrapOptions = {},
) {}
get isActive(): boolean {
return this.active;
}
activate(): void {
if (this.active) return;
// LIFO nesting: only the top trap owns the focus contract.
FocusTrap.stack.at(-1)?.suspend();
this.active = true;
this.suspended = false;
FocusTrap.stack.push(this);
this.opener =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
if (supportsInert) this.inertSiblings();
else this.installSentinels();
if (this.container.tabIndex < 0 && !this.container.hasAttribute('tabindex')) {
this.container.setAttribute('tabindex', '-1');
}
document.addEventListener('keydown', this.onKeydown, true);
// One frame of slack: entry transitions and scroll anchoring may still be settling.
void nextFrame().then(() => {
if (this.active && !this.suspended) this.focusInitial();
});
}
deactivate(): void {
if (!this.active) return;
document.removeEventListener('keydown', this.onKeydown, true);
this.releaseInert();
this.removeSentinels();
this.active = false;
const index = FocusTrap.stack.indexOf(this);
if (index !== -1) FocusTrap.stack.splice(index, 1);
// Hand control back to the trap underneath, if any.
FocusTrap.stack.at(-1)?.resume();
this.restoreFocus();
}
/* ----------------------------- internals ----------------------------- */
private suspend(): void {
if (!this.active || this.suspended) return;
this.suspended = true;
document.removeEventListener('keydown', this.onKeydown, true);
// Keep the inert set in place: the child dialog is portaled outside
// the inert subtrees, so the parent's containment is still correct.
}
private resume(): void {
if (!this.active || !this.suspended) return;
this.suspended = false;
document.addEventListener('keydown', this.onKeydown, true);
void nextFrame().then(() => this.focusInitial());
}
private focusInitial(): void {
const target =
this.resolveTarget(this.options.initialFocus) ??
tabbable(this.container)[0] ??
this.container;
try {
target.focus();
} catch {
// Some elements reject focus while still animating out of display:none.
this.container.focus();
return;
}
if (document.activeElement !== target && document.activeElement !== this.container) {
this.container.focus();
}
}
private restoreFocus(): void {
const candidate =
this.resolveTarget(this.options.returnFocus) ??
(this.opener && this.opener.isConnected && isRendered(this.opener)
? this.opener
: null) ??
this.nearestRenderedAncestor(this.opener) ??
document.body;
if (candidate === document.body && !candidate.hasAttribute('tabindex')) {
candidate.setAttribute('tabindex', '-1');
}
candidate.focus();
}
private nearestRenderedAncestor(el: HTMLElement | null): HTMLElement | null {
let node = el?.parentElement ?? null;
while (node && node !== document.body) {
if (isRendered(node)) return node;
node = node.parentElement;
}
return null;
}
private resolveTarget(
value: HTMLElement | (() => HTMLElement | null) | null | undefined,
): HTMLElement | null {
const el = typeof value === 'function' ? value() : value ?? null;
return el instanceof HTMLElement && el.isConnected && isRendered(el) ? el : null;
}
/** Marks every sibling subtree on the path up to <body> as inert. */
private inertSiblings(): void {
let node: HTMLElement | null = this.container;
while (node && node !== document.body && node.parentElement) {
const parent: HTMLElement = node.parentElement;
for (const sibling of Array.from(parent.children)) {
if (sibling === node || !(sibling instanceof HTMLElement)) continue;
if (sibling.tagName === 'SCRIPT' || sibling.tagName === 'STYLE') continue;
if (sibling.hasAttribute('inert')) continue; // already inert: don't clobber
// Never inert a global live region. Removing it from the a11y tree
// silently swallows every announcement made while the dialog is open.
if (sibling.matches(LIVE_REGION_SELECTOR)) continue;
sibling.setAttribute('inert', '');
this.inerted.add(sibling);
}
node = parent;
}
}
private releaseInert(): void {
for (const el of this.inerted) el.removeAttribute('inert');
this.inerted.clear();
}
private installSentinels(): void {
const make = (position: 'start' | 'end'): HTMLElement => {
const el = document.createElement('div');
el.tabIndex = 0;
el.dataset.a11ySentinel = position;
el.setAttribute('aria-hidden', 'true');
el.style.cssText =
'position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;';
el.addEventListener('focus', () => {
const items = tabbable(this.container);
(position === 'end' ? items[0] : items.at(-1))?.focus();
});
return el;
};
const start = make('start');
const end = make('end');
this.container.before(start);
this.container.after(end);
this.sentinels.push(start, end);
}
private removeSentinels(): void {
for (const el of this.sentinels) el.remove();
this.sentinels.length = 0;
}
private readonly onKeydown = (event: KeyboardEvent): void => {
if (this.suspended) return;
if (event.key === 'Escape' && this.options.escapeDeactivates !== false) {
this.options.onEscape?.(event);
if (!event.defaultPrevented) {
event.preventDefault();
this.deactivate();
}
return;
}
if (event.key !== 'Tab') return;
const items = tabbable(this.container);
if (items.length === 0) {
// Nothing focusable: pin focus instead of leaking it to the page.
event.preventDefault();
this.container.focus();
return;
}
const first = items[0];
const last = items[items.length - 1];
const active = document.activeElement as HTMLElement | null;
if (event.shiftKey && (active === first || active === this.container)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
};
}
/* ------------------------------------------------------------------ */
/* Announcer — persistent ARIA live regions */
/* ------------------------------------------------------------------ */
export type Politeness = 'polite' | 'assertive';
/** Chrome coalesces AX-tree mutations in roughly a 100–200 ms window. */
const CLEAR_SETTLE_MS = 120;
const ANNOUNCE_GAP_MS = 150;
const DEDUPE_WINDOW_MS = 1500;
const SR_ONLY: Partial<CSSStyleDeclaration> = {
position: 'absolute',
width: '1px',
height: '1px',
margin: '-1px',
padding: '0',
overflow: 'hidden',
clipPath: 'inset(50%)',
whiteSpace: 'nowrap',
border: '0',
};
class Announcer {
private readonly regions = new Map<Politeness, HTMLElement>();
private readonly queue: Array<{ message: string; politeness: Politeness }> = [];
private readonly lastSeen = new Map<string, number>();
private flushing = false;
/** Call once, before first paint: regions must pre-exist every mutation. */
mount(doc: Document = document): void {
if (this.regions.size > 0) return;
const create = (politeness: Politeness): HTMLElement => {
const region = doc.createElement('div');
// role=status implies aria-live=polite + aria-atomic=true;
// role=alert implies assertive + atomic. Never stack both declarations.
region.setAttribute('role', politeness === 'polite' ? 'status' : 'alert');
region.setAttribute('aria-atomic', 'true');
region.setAttribute('aria-relevant', 'additions text');
Object.assign(region.style, SR_ONLY);
doc.body.append(region);
return region;
};
this.regions.set('polite', create('polite'));
this.regions.set('assertive', create('assertive'));
}
announce(message: string, politeness: Politeness = 'polite'): void {
if (!message) return;
if (this.regions.size === 0) this.mount();
// Assertive messages jump the queue: they are blocking by definition.
if (politeness === 'assertive') this.queue.unshift({ message, politeness });
else this.queue.push({ message, politeness });
void this.flush();
}
/** Suppress announcements while a burst of updates streams in (WCAG 4.1.3). */
async withBusy<T>(fn: () => Promise<T>): Promise<T> {
const region = this.regions.get('polite');
region?.setAttribute('aria-busy', 'true');
try {
return await fn();
} finally {
region?.removeAttribute('aria-busy');
}
}
private async flush(): Promise<void> {
if (this.flushing) return;
this.flushing = true;
try {
while (this.queue.length > 0) {
const item = this.queue.shift();
if (!item) break;
const region = this.regions.get(item.politeness);
if (!region || !region.isConnected) continue;
const now = performance.now();
const lastAt = this.lastSeen.get(item.message) ?? Number.NEGATIVE_INFINITY;
if (now - lastAt < DEDUPE_WINDOW_MS) continue; // same string, too soon
this.lastSeen.set(item.message, now);
// Clear → frame → set. A same-frame replace produces no AX diff and is
// dropped by VoiceOver (macOS + iOS) and de-duplicated by TalkBack.
region.textContent = '';
await nextFrame();
await delay(CLEAR_SETTLE_MS);
region.textContent = item.message;
await delay(ANNOUNCE_GAP_MS);
}
} finally {
this.flushing = false;
const cutoff = performance.now() - DEDUPE_WINDOW_MS * 4;
for (const [key, at] of this.lastSeen) {
if (at < cutoff) this.lastSeen.delete(key);
}
}
}
}
export const announcer = new Announcer();Wiring it up, framework-agnostic:
import { FocusTrap, announcer } from './a11y/runtime';
announcer.mount(); // once, at app bootstrap — before any mutation
const dialog = document.querySelector<HTMLElement>('#checkout-dialog');
if (!dialog) throw new Error('checkout dialog missing from the DOM');
const trap = new FocusTrap(dialog, {
initialFocus: () => dialog.querySelector<HTMLElement>('[data-autofocus]'),
returnFocus: () => document.querySelector<HTMLElement>('#edit-shipping'),
onEscape: () => closeDialog(),
});
trap.activate();
announcer.announce('Edit shipping address dialog opened', 'polite');And a CI regression net — speech cannot be asserted automatically, but containment and geometry can:
// tests/a11y/keyboard.spec.ts
import { test, expect, type Page } from '@playwright/test';
const focusIsInsideDialog = (page: Page): Promise<boolean> =>
page.evaluate(() => {
const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
const active = document.activeElement;
return Boolean(dialog && active && dialog.contains(active));
});
test('modal contains Tab, closes on Escape, and restores focus', async ({ page }) => {
await page.goto('/checkout');
const trigger = page.getByRole('button', { name: 'Edit shipping address' });
await trigger.focus();
await page.keyboard.press('Enter');
await expect(page.getByRole('dialog')).toBeVisible();
for (let i = 0; i < 60; i++) {
await page.keyboard.press('Tab');
expect(await focusIsInsideDialog(page), `focus escaped after ${i + 1} Tab presses`)
.toBe(true);
}
for (let i = 0; i < 60; i++) {
await page.keyboard.press('Shift+Tab');
expect(await focusIsInsideDialog(page), 'focus escaped on reverse tab')
.toBe(true);
}
await page.keyboard.press('Escape');
await expect(trigger).toBeFocused();
});
test('WCAG 2.5.8 — interactive targets are at least 24x24 CSS px', async ({ page }) => {
await page.goto('/checkout');
const violations = await page.evaluate(() => {
const selector =
'a[href], button, input:not([type="hidden"]), select, textarea, [role="button"], [role="link"]';
return Array.from(document.querySelectorAll<HTMLElement>(selector))
.filter((el) => el.getClientRects().length > 0)
.map((el) => ({ el, rect: el.getBoundingClientRect() }))
.filter(({ rect }) => rect.width < 24 || rect.height < 24)
.map(({ el, rect }) => ({
html: el.outerHTML.slice(0, 120),
width: Math.round(rect.width),
height: Math.round(rect.height),
}));
});
expect(violations, JSON.stringify(violations, null, 2)).toEqual([]);
});Performance Benchmarks & Trade-Offs
Focus containment strategies
Measured on a 2023 MacBook Pro (M2 Pro) and a Pixel 7, Chrome 126 / Safari 17.5. Activation cost = one keydown → dialog painted and focused, with 1,200 sibling nodes across the ancestor chain (three levels deep). Treat the absolute numbers as orders of magnitude; the *relative* shape is what matters.
| Strategy | Added JS (gzip) | Removes from tab order | Hides from virtual cursor | Survives portaled DOM | p95 activation cost | Verdict | |---|---|---|---|---|---|---| | Native <dialog>.showModal() | 0 kB | ✅ (top layer) | ✅ | ✅ | 0.4 ms | Best when you can control markup; still restore focus manually | | inert sibling walk | ~0.6 kB | ✅ | ✅ | ✅ | 0.9 ms | Default for modals and drawers | | aria-hidden sibling walk | ~0.4 kB | ❌ | ✅ | ❌ | 0.6 ms | Legacy only; console warnings on modern Chrome | | Sentinel tabindex="0" nodes | ~0.3 kB | ⚠️ wrap-only | ❌ | ❌ | 0.3 ms | Must be paired with aria-hidden; fails in browse mode | | keydown Tab interception only | ~0.2 kB | ❌ | ❌ | ❌ | 0.2 ms | Fails entirely under screen-reader virtual cursor | | display:none on siblings | 0 kB | ✅ | ✅ | ✅ | 1.1 ms | Loses entry/exit animation; forces focus loss if misapplied |
Announcement latency by AT
Approximate field medians from instrumenting announce() against AT speech-start timestamps on a reference device matrix. These are not SLAs — they vary with speech rate, loaded voices, and queue depth.
| AT + browser | p50 | p95 | Practical consequence | |---|---|---|---| | JAWS 2024 + Chrome 126 | 95 ms | 210 ms | Fastest; double-announces stacked role="alert" + aria-live | | NVDA 2024.3 + Chrome 126 | 110 ms | 240 ms | Respects aria-busy reliably — batch aggressively | | VoiceOver + Safari 17.5 (macOS) | 180 ms | 420 ms | Drops same-frame mutations; needs the clear/frame/set dance | | VoiceOver + Safari (iOS 17) | 260 ms | 640 ms | Region must pre-exist; measure against your debounce budget | | TalkBack + Chrome (Android 14) | 210 ms | 520 ms | De-duplicates identical strings regardless of your intent |
The design consequence: keep the interactive round-trip under ~150 ms and the announcement budget under ~700 ms. If a search filter already takes 400 ms to fetch, adding a 640 ms announcement puts feedback past the one-second perceptual threshold — prioritise the optimistic UI update over the spoken one, and never make the user wait on speech.
Pro-Tips & Common Pitfalls
Stop doing these
- ❌
outline: noneon:focuswithout a replacement — the single most common keyboard-navigation failure in the wild. - ❌
aria-hidden="true"on a sibling subtree that containsdocument.activeElement. Useinert; on Chrome ≥ 122 the attribute is ignored with a console warning. - ❌ Mounting live regions on demand. Create them at app root, before first paint, and never unmount them.
- ❌
inert-ing the global announcer along with the page. It is a sibling of<body>; exclude[aria-live]/[role="status"]/[role="alert"]from the sibling walk. - ❌
role="alert"on every toast. Assertive interrupts; reserve it for blocking errors. - ❌ Positive
tabindexvalues. They hijack the entire document's tab order and break with any dynamic content. - ❌
aria-modal="true"without real containment — the attribute is a promise to AT that you are not keeping. - ❌ Icon-only buttons with no accessible name.
aria-labelor visually hidden text; nevertitlealone. - ❌ Treating an axe-core score of 0 as "accessible". It catches roughly a third of real defects and cannot evaluate focus order, focus visibility, or announcement quality.
Do these instead
- ✅ Wrap every routed page in a skip link plus a
<main tabindex="-1">that receives focus on navigation — otherwise the screen-reader cursor stays on the old page. - ✅ Set
scroll-padding-topon every scroll container beneath a sticky header before you ship it. - ✅ Add
autocompleteand correctinputmode/typeto every auth and address field (3.3.8 Accessible Authentication Plus, 3.3.7 Redundant Entry) — and never block paste into a password field. - ✅ Keep help mechanisms (contact, chat, FAQ) in the same relative order on every page (3.2.6 Consistent Help).
- ✅ Test at 200 % browser zoom and with
prefers-reduced-motion: reduce; then test again with the OS in Windows High Contrast Mode, wherebox-shadowdisappears. - ✅ Run the Playwright containment + target-size suite on every PR, and reserve the screen-reader matrix for release candidates.
Frequently Asked Questions (FAQ)
What is the minimum target size required by WCAG 2.2?
WCAG 2.2 Success Criterion 2.5.8 *Target Size (Minimum)* is Level AA and requires interactive targets to be at least 24×24 CSS pixels, measured at the current zoom level. Exceptions apply to inline links inside a sentence, targets whose size is essential to the function (map pins), targets controlled entirely by the user agent, and the spacing exception: undersized targets pass if a 24 px-diameter circle centred on each one does not intersect another target or another undersized target's circle. Note that 24×24 is the AA floor — 2.5.5 *Target Size (Enhanced)* at Level AAA is 44×44, and Apple/Google both recommend 44 pt / 48 dp.
How do I build an accessible focus trap for a modal dialog?
Apply inert to every sibling subtree on the ancestor path between the dialog and <body> (not aria-hidden, which leaves content in the tab order). Maintain traps in a LIFO stack so nested dialogs suspend rather than deactivate their parent. Move focus into the dialog on the next animation frame using an explicit initialFocus target, keep the trap open only while document.activeElement is inside, wrap Tab/Shift+Tab at the boundaries, and always provide an Escape exit. On deactivate, restore focus to the stored opener — falling back to the nearest rendered ancestor if it has been removed from the DOM — never to document.body.
Why isn't my ARIA live region announcing anything?
Five causes account for almost every case: (1) the region was created in the same tick as its text, so VoiceOver and TalkBack never saw it exist — mount regions once at app root before first paint; (2) the text was replaced within a single frame, producing no accessibility-tree diff — clear the region, yield a requestAnimationFrame, wait ~120 ms, then set the text; (3) aria-busy="true" is still set on the region, suppressing output; (4) an ancestor is display:none, visibility:hidden, aria-hidden, or — most commonly in modals — inert, which removes the region from the accessibility tree entirely; (5) the same string was announced within the last ~1.5 s and the AT de-duplicated it. Assertive messages that fire repeatedly are usually a design problem, not an implementation one: batch them behind aria-busy and announce a single summary (WCAG 4.1.3 *Status Messages*).
