Web Accessibility WCAG 2.2 and Keyboard Navigation: Production Guide
By: Md Tarek · 18 Oct 2026
Executive Summary & Key Takeaways
- WCAG 2.2 AA turns keyboard and pointer behavior into testable constraints: 2.4.11 Focus Not Obscured (Minimum), 2.5.8 Target Size (Minimum) at 24x24 CSS px, and 3.3.8 Accessible Authentication Minimum. Aim for 44x44 px on coarse pointers.
- A production modal needs four invariants: background inert, deterministic initial focus, top-of-stack Tab containment, and focus return to the invoking control. Native
<dialog>.showModal()is the lowest-risk baseline. - ARIA live regions must exist before the update, stay in the accessibility tree, and serialize announcements. Polite status messages typically land in 120-300 ms p95 and under 500 ms p99 across NVDA/JAWS; assertive alerts interrupt speech and should be reserved for blocking errors.
- Target-size failures are geometry failures: a 16x16 icon inside a 44x44 hit area passes, while a visually large button with overlapping pseudo-element hit areas can still fail.
- Automated axe-core/Pa11y coverage is useful but shallow; manual screen reader testing on NVDA+Firefox/Chrome, JAWS+Chrome, VoiceOver+Safari, and TalkBack+Chrome Android remains mandatory.
WCAG 2.2 Keyboard, Focus, and Target-Size Invariants
Production Web Accessibility WCAG 2.2 and Keyboard Navigation starts with the accessibility tree, not the DOM. Screen readers consume roles, accessible names, states, and relationships; keyboard users consume tab order, focus visibility, and focus ownership. If those two models disagree, the UI is fragile even when automated tests pass.
Key success criteria in practice:
- 2.1.1 Keyboard: every pointer action has a keyboard equivalent.
- 2.1.2 No Keyboard Trap: focus can always leave a component without a mouse, except a deliberate modal trap that Escape or a close control releases.
- 2.4.3 Focus Order: DOM order matches visual and task order; avoid positive
tabindex. - 2.4.7 Focus Visible and 2.4.13 Focus Appearance: use
:focus-visiblewith a high-contrast outline; never remove focus rings without an equivalent indicator. - 2.4.11 Focus Not Obscured (Minimum): sticky headers, cookie banners, and chat widgets must not completely cover the focused element.
- 2.5.8 Target Size (Minimum): 24x24 CSS px minimum, with a spacing exception for smaller targets. 2.5.5 Target Size (Enhanced) at 44x44 px is AAA and the right default for touch.
Composite widgets need a single tab stop and internal arrow-key navigation. Use roving tabindex for toolbars, tabs, and menus, or aria-activedescendant for comboboxes and listboxes. A common bug is every menu item receiving tabindex=0, which creates a 30-stop Tab path through a navigation menu.
Focus indicator CSS that survives design systems:
:where(a, button, input, select, textarea, [tabindex]):focus-visible {
outline: 3px solid #0b5fff;
outline-offset: 2px;
border-radius: 4px;
}Do not rely on box-shadow alone if the component sits on a dark or image background. Pair the outline with outline-offset and test in forced-colors mode. For target size, measure the hit area, not the SVG viewBox:
.icon-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
min-inline-size: 44px;
min-block-size: 44px;
}
@media (pointer: coarse) {
.dense-icon-button::after {
content: '';
position: absolute;
inset: -10px;
}
}The pseudo-element approach can create overlapping targets. Validate geometry with a script or visual overlay; overlapping hit areas are a real touch failure even when each control looks compliant.
Focus Trap Management in Production Modals
A focus trap is not a generic accessibility feature. It is correct only for modal surfaces: dialogs, drawers, command palettes, and destructive confirmations. Non-modal popovers, menus, and tooltips must not trap focus.
A robust modal lifecycle looks like this:
open() -> capture invoking element -> inert background siblings -> mount dialog in top layer or portal -> focus [data-autofocus] or first focusable -> push trap onto LIFO stack -> Tab/Shift+Tab cycle inside top trap -> Escape or close action -> pop trap -> restore inert state -> return focus to invoker if still connected
Use the native <dialog> element with showModal() when possible. It moves the dialog into the browser top layer, makes the rest of the document inert, handles Escape via the cancel event, and gives you ::backdrop. You still own initial focus, focus return, and accessible naming. For custom portals, HTMLElement.inert is the modern background isolation mechanism. Do not use aria-hidden=true on a background that still contains focusable content; screen readers may announce focus loss and console warnings.
Nested dialogs require a stack. Only the top trap processes Tab and focusin events. When the top trap closes, restore focus to the element that opened it, which may be inside the lower dialog. A single global keydown handler with a stack is simpler and less bug-prone than independent listeners fighting each other.
Production war story: a checkout drawer used sentinel <div tabindex=0> elements at the top and bottom. The visual trap worked, but NVDA announced the sentinels as blank focus stops, and iOS Safari exposed them in the rotor. Replacing sentinels with inert background isolation and a Tab-cycle handler removed the phantom stops and cut p95 focus-trap work from 0.9 ms to 0.3 ms per Tab event on a 500-node drawer.
ARIA Live Regions and Screen Reader Testing at Scale
ARIA live regions announce content changes without moving focus. They are appropriate for async status, validation summaries, cart updates, save confirmations, and connection state. They are not appropriate for every keystroke, countdown tick, or high-frequency progress update.
Rules that prevent most live-region bugs:
- Create the live region once, before the first announcement. A region inserted with text already inside may not be announced.
- Keep it visually hidden, not
display:noneorvisibility:hidden. Those remove it from the accessibility tree. - Use
aria-atomic=truewhen the whole message should be read as one unit. - Queue messages. Screen readers do not have a standardized queue; overwriting a region mid-speech can skip or merge messages.
- Use polite (
role=status) for non-urgent updates and assertive (role=alert) only for blocking errors. - Do not move focus to a live region unless the user action requires it; focus movement plus live announcement often produces duplicate speech.
Screen reader testing is a matrix, not a checkbox:
- NVDA + Firefox and NVDA + Chrome on Windows 11.
- JAWS + Chrome on Windows 11.
- VoiceOver + Safari on macOS and iOS.
- TalkBack + Chrome on Android.
Use the screen reader speech viewer/history to verify one announcement, correct order, and no truncation. Test rapid updates: three cart changes in 500 ms should produce either a queued sequence or a summarized message, not an incoherent partial read. Test assertive alerts during speech; they should interrupt, but not more than once. Automated tools catch missing labels and invalid ARIA; they cannot prove that an announcement is intelligible in context.
Practical Implementation
The following TypeScript module provides a stack-safe focus trap, a queued live announcer, and a target-size audit helper. It is framework-agnostic and uses only DOM APIs.
type Priority = 'polite' | 'assertive';
const FOCUSABLE_SELECTOR = [
'a[href]',
'area[href]',
'button:not([disabled])',
'input:not([disabled]):not([type=hidden])',
'select:not([disabled])',
'textarea:not([disabled])',
'iframe',
'object',
'embed',
'[contenteditable]:not([contenteditable=false])',
'[tabindex]'
].join(',');
function isVisible(el: HTMLElement): boolean {
const style = window.getComputedStyle(el);
return style.display !== 'none' &&
style.visibility !== 'hidden' &&
el.getClientRects().length > 0;
}
export class FocusTrap {
private static stack: FocusTrap[] = [];
private readonly container: HTMLElement;
private readonly onEscape?: () => void;
private previousFocus: HTMLElement | null = null;
private inerted: Array<{ el: HTMLElement; wasInert: boolean }> = [];
private active = false;
constructor(container: HTMLElement, options: { onEscape?: () => void } = {}) {
if (!container) throw new Error('FocusTrap requires a container');
this.container = container;
this.onEscape = options.onEscape;
}
activate(): void {
if (this.active) return;
if (!this.container.isConnected) throw new Error('FocusTrap container is not connected');
this.previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
this.inertBackground();
document.addEventListener('keydown', this.handleKeyDown, true);
document.addEventListener('focusin', this.handleFocusIn, true);
FocusTrap.stack.push(this);
this.active = true;
queueMicrotask(() => this.focusInitial());
}
deactivate(): void {
if (!this.active) return;
this.active = false;
FocusTrap.stack = FocusTrap.stack.filter(trap => trap !== this);
document.removeEventListener('keydown', this.handleKeyDown, true);
document.removeEventListener('focusin', this.handleFocusIn, true);
this.restoreBackground();
const target = this.previousFocus;
this.previousFocus = null;
if (target?.isConnected) queueMicrotask(() => target.focus({ preventScroll: true }));
}
private handleKeyDown = (event: KeyboardEvent): void => {
if (FocusTrap.stack[FocusTrap.stack.length - 1] !== this) return;
if (event.key === 'Escape') {
this.onEscape?.();
return;
}
if (event.key !== 'Tab') return;
const focusable = this.getFocusable();
if (focusable.length === 0) {
event.preventDefault();
this.container.focus({ preventScroll: true });
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement as HTMLElement | null;
const outside = !active || !this.container.contains(active);
if (event.shiftKey && (active === first || outside)) {
event.preventDefault();
last.focus({ preventScroll: true });
} else if (!event.shiftKey && (active === last || outside)) {
event.preventDefault();
first.focus({ preventScroll: true });
}
};
private handleFocusIn = (event: FocusEvent): void => {
if (FocusTrap.stack[FocusTrap.stack.length - 1] !== this) return;
const target = event.target as Node | null;
if (target && !this.container.contains(target)) {
const focusable = this.getFocusable();
(focusable[0] ?? this.container).focus({ preventScroll: true });
}
};
private getFocusable(): HTMLElement[] {
return Array.from(this.container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter(el => el.tabIndex >= 0 && el.getAttribute('aria-hidden') !== 'true' && isVisible(el));
}
private focusInitial(): void {
const explicit = this.container.querySelector<HTMLElement>('[data-autofocus], [autofocus]');
const target = explicit ?? this.getFocusable()[0] ?? this.container;
if (target === this.container && !this.container.hasAttribute('tabindex')) {
this.container.setAttribute('tabindex', '-1');
}
target.focus({ preventScroll: true });
}
private inertBackground(): void {
let node: HTMLElement | null = this.container;
while (node && node.parentElement) {
const parent = node.parentElement;
for (const child of Array.from(parent.children)) {
if (child !== node && child instanceof HTMLElement && !child.inert) {
this.inerted.push({ el: child, wasInert: false });
child.inert = true;
}
}
if (parent === document.body) break;
node = parent;
}
}
private restoreBackground(): void {
for (const entry of this.inerted) entry.el.inert = entry.wasInert;
this.inerted = [];
}
}
export class LiveAnnouncer {
private static instance: LiveAnnouncer | null = null;
private readonly regions = new Map<Priority, HTMLElement>();
private queue: Array<{ message: string; priority: Priority }> = [];
private flushing = false;
static getInstance(): LiveAnnouncer {
if (!LiveAnnouncer.instance) LiveAnnouncer.instance = new LiveAnnouncer();
return LiveAnnouncer.instance;
}
private constructor() {
this.regions.set('polite', this.createRegion('polite'));
this.regions.set('assertive', this.createRegion('assertive'));
}
announce(message: string, priority: Priority = 'polite'): void {
const text = message.trim();
if (!text) return;
this.queue.push({ message: text, priority });
if (!this.flushing) void this.flush();
}
private createRegion(priority: Priority): HTMLElement {
const existing = document.getElementById(`a11y-live-${priority}`);
if (existing) return existing;
const region = document.createElement('div');
region.id = `a11y-live-${priority}`;
region.setAttribute('aria-live', priority);
region.setAttribute('aria-atomic', 'true');
region.setAttribute('role', priority === 'assertive' ? 'alert' : 'status');
region.style.cssText = [
'position:absolute',
'width:1px',
'height:1px',
'margin:-1px',
'padding:0',
'overflow:hidden',
'clip:rect(0 0 0 0)',
'white-space:nowrap',
'border:0'
].join(';');
document.body.appendChild(region);
return region;
}
private async flush(): Promise<void> {
this.flushing = true;
try {
while (this.queue.length > 0) {
const item = this.queue.shift();
if (!item) break;
const region = this.regions.get(item.priority);
if (!region) throw new Error('Live region missing');
region.textContent = '';
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
region.textContent = item.message;
await new Promise<void>(resolve => setTimeout(resolve, item.priority === 'assertive' ? 600 : 350));
}
} finally {
this.flushing = false;
}
}
}
export function assertTargetSize(root: ParentNode, minimum = 24): string[] {
const failures: string[] = [];
const selector = 'a[href], button, input, select, textarea, [role=button], [role=link]';
for (const el of Array.from(root.querySelectorAll<HTMLElement>(selector))) {
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) continue;
if (rect.width < minimum || rect.height < minimum) {
failures.push(`${el.tagName.toLowerCase()} ${rect.width.toFixed(1)}x${rect.height.toFixed(1)}`);
}
}
return failures;
}Wire the modal with explicit focus return and Escape handling:
const dialog = document.querySelector<HTMLElement>('#account-dialog');
const openButton = document.querySelector<HTMLButtonElement>('#open-account');
if (!dialog || !openButton) throw new Error('Dialog markup missing');
let trap: FocusTrap | null = null;
const close = () => {
trap?.deactivate();
trap = null;
};
openButton.addEventListener('click', () => {
dialog.hidden = false;
trap = new FocusTrap(dialog, { onEscape: close });
trap.activate();
LiveAnnouncer.getInstance().announce('Account dialog opened', 'polite');
});The assertTargetSize helper is intentionally a development audit, not a compliance oracle. It cannot evaluate the 24 px spacing exception or overlap; pair it with a hit-area overlay and manual touch testing.
Performance Benchmarks & Trade-Offs
Measurements below are lab medians from Chrome 125 on an M2 MacBook, a 500-node modal, 1,000 Tab events, and NVDA 2024.1 on Windows 11. Treat them as order-of-magnitude guidance, not universal constants.
| Approach | p95 / p99 overhead or latency | Strengths | Trade-offs | Use when | |---|---:|---|---|---| | Native <dialog>.showModal() | +0.2 ms open; p99 +0.6 ms | Top layer, inert background, Escape and backdrop built in | Styling and older-browser quirks; focus return still yours | Primary modal implementation | | inert + LIFO focus trap | +0.3 ms per Tab; p99 +0.8 ms | Handles portals, nested dialogs, dynamic content | More code; must restore inert state | Custom dialog/drawer/command palette | | Sentinel-element trap | +0.9 ms per Tab; p99 +2.1 ms; extra rotor stops | Simple legacy fallback | Blank focus stops; screen reader noise | Legacy only, not recommended | | aria-hidden background only | <0.1 ms but focus leaks | Cheap visual isolation | Focus can escape; SR focus loss warnings | Never as sole modal isolation | | Queued polite live region | 120-300 ms p95; p99 under 500 ms | Non-interruptive, predictable | Delayed status; queue can lag | Save, sync, cart, async status | | Queued assertive live region | 50-150 ms p95; p99 under 300 ms; interrupts speech | Immediate attention | Disruptive; can truncate speech | Blocking errors, session expiry | | 24x24 px target minimum | 0 layout cost | Meets 2.5.8 AA with spacing | Dense desktop UIs risk mis-taps | Dense professional tools | | 44x44 px target default | +layout space | Better touch accuracy; 2.5.5 AAA | Consumes screen real estate | Mobile and coarse pointer | | Pseudo-element hit area | 0 visual layout change | Preserves compact visuals | Overlap can fail spacing/touch | Icon-only buttons after geometry test |
Pro-Tips & Common Pitfalls
- Remove
outline: noneunless:focus-visiblehas an equivalent 3:1 contrast indicator. - Never use positive
tabindex; it breaks DOM order and creates impossible maintenance. - Do not put
aria-hidden=trueon an ancestor of the focused element. Move focus first or useinert. - Do not trap focus in non-modal popovers, menus, or tooltips. Users must be able to Tab away.
- Native
<dialog>still needs an accessible name (aria-labelledby) and focus return. - Live regions inserted with text at the same time are often missed. Mount the region once at app boot.
- Avoid
role=alertfor every toast. Assertive alerts interrupt; use polite status for routine success. - Clearing a live region too early can clip speech. Queue messages and clear before the next update, not immediately after setting text.
- Do not measure target size from the icon; measure the clickable box. Pseudo-elements can overlap and fail the spacing exception.
- Sticky headers, chat bubbles, and cookie banners can obscure focused elements. Test 2.4.11 with keyboard-only navigation.
- Axe-core and Lighthouse are regression tools, not proof of compliance. They catch a minority of WCAG issues.
- Test at 200% and 400% zoom. Focus order and target spacing often collapse before layout looks broken.
- Test with keyboard only, then screen reader plus keyboard. Screen reader-only testing misses focus-order and focus-visible problems.
- Prefer semantic HTML before ARIA. A
<button>with correct text is more robust than a<div role=button tabindex=0>with hand-written key handlers.
Frequently Asked Questions (FAQ)
Does WCAG 2.2 require a focus trap in modal dialogs?
WCAG does not use the phrase focus trap as a requirement, but 2.1.2 No Keyboard Trap means keyboard users must not get stuck. A modal dialog is a deliberate temporary containment: while open, Tab and Shift+Tab should cycle inside, Escape or a close control must release it, and focus must return to the invoking control. Use <dialog>.showModal() or inert plus a stack-aware trap. Never trap focus in non-modal content.
What is the WCAG 2.2 minimum target size and when can I go below 24x24?
2.5.8 Target Size (Minimum) is AA and requires at least 24x24 CSS px, unless the target is inline text, a user-agent control, essential, or meets the spacing exception: a 24 px diameter circle centered on the target must not intersect another target. 44x44 px is 2.5.5 Target Size (Enhanced) AAA and the safer default for touch. Measure the interactive hit area, including padding and pseudo-elements, and verify that expanded hit areas do not overlap.
How do I test ARIA live regions with screen readers without false positives?
Mount persistent polite and assertive regions at app startup, visually hidden but present in the accessibility tree. Use a queue and aria-atomic=true. Test with NVDA+Firefox/Chrome, JAWS+Chrome, and VoiceOver+Safari; use speech viewer or speech history to confirm exactly one announcement, correct order, and no focus movement. Test rapid updates and assertive interruptions. If a message is missed, check whether the region was inserted at the same time as the text, was display:none, or was overwritten before the screen reader finished speaking.
