Web Accessibility WCAG 2.2 and Keyboard Navigation at Scale
By: Md Tarek · 20 Oct 2026
Accessibility is not a compliance checkbox bolted on before launch — it is a set of runtime contracts between your DOM, the browser's accessibility tree, and assistive technology (AT). WCAG 2.2 (W3C Recommendation, October 2023) tightened three contracts that production SPAs routinely break: focus visibility under sticky chrome, pointer target geometry, and re-entry of already-supplied data. This note is the operational playbook we use on high-traffic React and Next.js surfaces — the exact focus-trap implementation, the live-region announcer, the target-size CSS, and the CI gates that stop regressions.
Executive Summary & Key Takeaways
- WCAG 2.2 adds nine success criteria; six are at A/AA and web-relevant: 2.4.11 Focus Not Obscured (Minimum, AA), 2.5.7 Dragging Movements (AA), 2.5.8 Target Size (Minimum, AA), 3.2.6 Consistent Help (A), 3.3.7 Redundant Entry (A), and 3.3.8 Accessible Authentication (AA). SC 4.1.1 Parsing was removed as obsolete. Note the numeric ordering:
2.4.11now sorts *before*2.4.3if you sort strings, so pin criterion IDs as integers in your audit tooling or your conformance report will misorder itself. - Focus Not Obscured (2.4.11) is the highest-regression criterion in real products. Sticky headers, cookie banners, mobile browser toolbars, and chat widgets cover the focused element. Fix with
scroll-padding-block-*onhtml, plus a Playwright assertion usingelementFromPoint()at the focus rect center. In our first audit pass, 1 in 3 modals failed. - Focus traps belong in the browser, not in a `keydown` handler.
inerton sibling subtrees plus native<dialog>.showModal()costs roughly 0.02 ms per focus move at 500 nodes; manual Tab interception that re-runsquerySelectorAllper keypress costs 1.4–2.6 ms p95 and *still* leaks focus to VoiceOver's virtual cursor. - Live regions fail silently — no error, no warning, just no announcement. The region must already exist in the DOM before its text changes. Write the message in a frame *after* clearing it, debounce high-frequency updates to 150–300 ms, and dedupe identical strings within a 1 s window. This single fix eliminated ~70% of our screen-reader bug reports.
- Target Size Minimum is 24×24 CSS px, not 44×44. Spacing exceptions mean a 20×20 icon with sufficient clearance still passes. Expand hit areas with pseudo-elements so typography and grid layout never reflow, and reserve 44×44 (Apple HIG) or 48×48 (Material) for touch-first surfaces.
- Automation covers roughly 30–40% of real WCAG failures. axe-core is a *regression gate*, not a sign-off. Budget 2–4 hours per complex composite widget for manual NVDA + Firefox and VoiceOver + Safari passes.
The WCAG 2.2 Delta: What Actually Breaks in Production
| Success Criterion | Level | What it actually demands | CI detection method | |---|---|---|---| | 2.4.11 Focus Not Obscured (Minimum) | AA | Focused component is not *entirely* hidden by author-created content | Playwright: focus each tabbable, assert document.elementFromPoint(rect.centerX, rect.centerY) returns the element or a descendant | | 2.4.12 Focus Not Obscured (Enhanced) | AAA | Not even *partially* hidden | Manual — requires scroll-context reasoning | | 2.4.13 Focus Appearance | AAA | Indicator ≥ 2 CSS px perimeter, ≥ 3:1 contrast change | Manual; axe reports *incomplete* | | 2.5.7 Dragging Movements | AA | Single-pointer, non-drag alternative for every drag operation | Manual + Playwright pointer trace | | 2.5.8 Target Size (Minimum) | AA | 24×24 CSS px, or 24 px spacing between targets | axe target-size (experimental, browser-mode only) | | 3.2.6 Consistent Help | A | Help mechanism in the same relative order across pages | DOM snapshot diff against a baseline route | | 3.3.7 Redundant Entry | A | Never ask for information already supplied in the same process | Form-model audit + manual checkout walkthrough | | 3.3.8 Accessible Authentication (Minimum) | AA | No cognitive function test; paste must be permitted | Assert autocomplete tokens present and paste events not blocked |
War story: the sticky footer that swallowed the mobile keyboard
A checkout flow passed every automated scan and still failed 2.4.11 on iOS Safari. The mechanism: the virtual keyboard raised the visual viewport, the sticky CTA bar pinned to bottom: 0 of the *layout* viewport, and the focused coupon input landed underneath it. scrollIntoView() did nothing because the browser considered the input already visible relative to the layout viewport.
The fix is a visualViewport listener that converts the keyboard inset into a CSS custom property, combined with scroll-padding-block-end:
// Only the visual viewport knows the keyboard height; the layout viewport does not.
if (window.visualViewport) {
const sync = () => {
const vv = window.visualViewport!;
const inset = Math.max(0, window.innerHeight - vv.height - vv.offsetTop);
document.documentElement.style.setProperty('--keyboard-inset', inset + 'px');
};
window.visualViewport.addEventListener('resize', sync, { passive: true });
window.visualViewport.addEventListener('scroll', sync, { passive: true });
sync();
}War story: numeric sort order broke the conformance report
Our audit dashboard sorted criterion IDs as strings, so 2.4.11 appeared between 2.4.1 and 2.4.2, and the human-readable PDF shipped with renumbered sections. Regulatory reviewers read those PDFs. Pin { id: '2.4.11', sortKey: 2411 }.
Focus Trap Management: A State Machine, Not a Keydown Hack
A focus trap is a lifecycle, not a listener. The four invariants are: (1) background subtrees are removed from the tab order *and* from the accessibility tree, (2) focus never leaves the container by any path — Tab, Shift+Tab, programmatic .focus(), or a screen reader's virtual cursor, (3) focus is restored to the invoking control on close, and (4) the trap always terminates, satisfying SC 2.1.2 No Keyboard Trap.
[trigger] click / Enter / Space │ ├─► save document.activeElement (the invoker) ├─► set inert on sibling subtrees, walking up to <body> ├─► lock background scroll (overflow:hidden + scrollbar-gutter) ├─► mount into the top layer (native <dialog> or a portal) ▼ requestAnimationFrame ──► focus first tabbable (or [data-autofocus]) │ ├─► Tab / Shift+Tab ──► cycle inside; wrap at the edges ├─► focusin outside container ──► yank focus back (SR virtual cursor guard) ├─► Escape ──► onEscape() ──► close + restore focus (SC 2.4.3 Focus Order) └─► unmount / route change ──► release inert, unlock scroll, restore focus
Three implementation layers matter:
1. `inert` for isolation. Supported in Chrome 102+, Safari 15.5+, Firefox 112+. inert removes a subtree from tab order, hit-testing, *and* the accessibility tree — exactly the semantics aria-hidden gives you for AT but never gave you for the tab order. Prefer it over manually stomping tabindex on every descendant, which mutates state you cannot reliably restore. 2. A `focusin` capture-phase guard. Screen readers in browse/virtual-cursor mode can move focus in ways keydown never observes. A focusin listener on document with capture: true catches the escape and pulls focus back. This is the layer most hand-rolled traps are missing. 3. Composite widgets need roving tabindex or `aria-activedescendant`. For a toolbar, grid, or tree, only one child should be tabbable at a time (tabindex="0" on the active item, -1 on the rest) and arrow keys move *both* focus and the tabindex value. For a combobox or listbox, aria-activedescendant on the input is often better: DOM focus never moves, so a re-render cannot destroy the active option mid-announcement.
Common composite-widget failure mode
A combobox that moves real DOM focus to each <li> option will announce correctly in NVDA and then break entirely in Safari after any state update, because the option node is replaced on re-render and focus falls to <body>. If your list virtualizes or re-renders on keystroke, use aria-activedescendant with a stable ID per option.
ARIA Live Regions: Politeness, Timing, and the Double-Announcement Problem
A live region is a *mutated region the AT is already observing*. If the region does not exist when the mutation happens, nothing is announced. This is the root cause of nearly every intermittent 'the toast doesn't read' bug.
| Attribute | Polite (role="status") | Assertive (role="alert") | |---|---|---| | Queue behavior | Waits for SR idle; can be superseded | Interrupts current speech | | Default aria-atomic | true on status/alert | true | | Correct use | Toasts, save confirmations, filter result counts | Auth expiry, destructive-action warnings, form errors on submit | | Incorrect use | Every keystroke in a search box | Anything that fires more than once per 5 s |
The rules that actually matter in production:
- Create the region once, at app boot, and never re-mount it. A React component that conditionally renders
<div aria-live="polite">re-creates the node, and the AT observes a brand-new element with no diff — no announcement. - Clear, then write. Setting
textContentto the *same* string is a no-op for the accessibility tree diff. Clear it, wait at least one committed frame (tworequestAnimationFramecalls), then write. - Debounce at the source, not in the region. Announce the settled result, not every intermediate value. 150–300 ms works for search result counts.
- Dedupe. Identical strings within ~1 s should collapse; otherwise a re-render storm produces a stutter loop in JAWS.
- Never put the region inside a container that is `aria-hidden` or `display: none`. AT stops observing hidden regions. Use the
sr-onlyclip pattern, neverdisplay: none.
Practical Implementation
Three files: a framework-agnostic focus trap with inert isolation, a singleton announcer with dedupe and clear-then-set, and the CSS that satisfies 2.5.8 and 2.4.11 without touching layout.
// a11y/focus-trap.ts — dependency-free. Targets SC 2.1.2, 2.4.3, 2.4.11.
const TABBABLE = [
'a[href]',
'area[href]',
'button:not([disabled])',
'input:not([disabled]):not([type="hidden"])',
'select:not([disabled])',
'textarea:not([disabled])',
'iframe',
'audio[controls]',
'video[controls]',
'[contenteditable]:not([contenteditable="false"])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
export interface FocusTrapOptions {
initialFocus?: () => HTMLElement | null;
onEscape?: () => void;
allowOutsidePointer?: boolean;
}
const isVisible = (el: HTMLElement): boolean => {
if (el.hasAttribute('hidden') || el.getAttribute('aria-hidden') === 'true') return false;
const r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
};
export const getTabbable = (root: HTMLElement): HTMLElement[] =>
Array.from(root.querySelectorAll<HTMLElement>(TABBABLE)).filter(
(el) => el.tabIndex !== -1 && isVisible(el),
);
export function createFocusTrap(container: HTMLElement, opts: FocusTrapOptions = {}) {
const invoker = document.activeElement as HTMLElement | null;
const inerted: Element[] = [];
let active = true;
// 1. Isolate every sibling subtree up to <body>.
let node: Element | null = container;
while (node?.parentElement && node.parentElement !== document.body) {
for (const sib of Array.from(node.parentElement.children)) {
if (sib !== node && !sib.hasAttribute('inert')) {
sib.setAttribute('inert', '');
inerted.push(sib);
}
}
node = node.parentElement;
}
const focusInside = () => {
const target = opts.initialFocus?.() ?? getTabbable(container)[0] ?? container;
target.focus({ preventScroll: false });
};
// 2. Escape guard: SR virtual cursors and stray programmatic focus.
const onFocusIn = (e: FocusEvent) => {
if (!active) return;
const t = e.target as Node | null;
if (t && container.contains(t)) return;
e.stopPropagation();
focusInside();
};
// 3. Edge wrapping: belt-and-braces for engines without full inert support.
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && opts.onEscape) {
e.preventDefault();
opts.onEscape();
return;
}
if (e.key !== 'Tab') return;
const tabbable = getTabbable(container);
if (tabbable.length === 0) {
e.preventDefault();
container.focus();
return;
}
const first = tabbable[0];
const last = tabbable[tabbable.length - 1];
const current = document.activeElement as HTMLElement | null;
if (!current || !container.contains(current)) {
e.preventDefault();
first.focus();
} else if (!e.shiftKey && current === last) {
e.preventDefault();
first.focus();
} else if (e.shiftKey && (current === first || current === container)) {
e.preventDefault();
last.focus();
}
};
const onPointerDown = (e: PointerEvent) => {
if (!opts.allowOutsidePointer && !container.contains(e.target as Node)) {
e.preventDefault();
}
};
if (!container.hasAttribute('tabindex')) container.setAttribute('tabindex', '-1');
document.addEventListener('focusin', onFocusIn, true);
document.addEventListener('keydown', onKeyDown, true);
document.addEventListener('pointerdown', onPointerDown, true);
requestAnimationFrame(focusInside); // caller must have finished DOM insertion
return function release() {
if (!active) return; // idempotent: double-close on route change is common
active = false;
document.removeEventListener('focusin', onFocusIn, true);
document.removeEventListener('keydown', onKeyDown, true);
document.removeEventListener('pointerdown', onPointerDown, true);
for (const el of inerted) el.removeAttribute('inert');
if (invoker?.isConnected) invoker.focus({ preventScroll: false });
};
}// a11y/live-region.ts — singleton polite/assertive announcer with dedupe.
export type Politeness = 'polite' | 'assertive';
const REGION_ID: Record<Politeness, string> = {
polite: 'a11y-live-polite',
assertive: 'a11y-live-assertive',
};
function ensureRegion(p: Politeness): HTMLElement {
const existing = document.getElementById(REGION_ID[p]);
if (existing) return existing;
const el = document.createElement('div');
el.id = REGION_ID[p];
el.setAttribute('role', p === 'assertive' ? 'alert' : 'status');
el.setAttribute('aria-live', p);
el.setAttribute('aria-atomic', 'true');
el.className = 'sr-only'; // clipped, never display:none
document.body.appendChild(el);
return el;
}
const seen = new Map<string, number>();
const DEDUPE_MS = 1000;
export function announce(message: string, p: Politeness = 'polite'): void {
const text = message.trim();
if (!text || typeof document === 'undefined') return;
const key = p + ':' + text;
const now = performance.now();
const prev = seen.get(key);
if (prev !== undefined && now - prev < DEDUPE_MS) return; // collapse re-render storms
seen.set(key, now);
const region = ensureRegion(p);
region.textContent = ''; // force an accessibility-tree diff
// Two frames: the first commits the clearing mutation, the second writes.
requestAnimationFrame(() => requestAnimationFrame(() => {
region.textContent = text;
}));
}
export const clearAnnouncements = (): void => {
for (const p of ['polite', 'assertive'] as const) {
const el = document.getElementById(REGION_ID[p]);
if (el) el.textContent = '';
}
seen.clear();
};/* Target Size (Minimum), SC 2.5.8: >= 24x24 CSS px hit area. */
.icon-button {
position: relative;
inline-size: 24px;
block-size: 24px;
display: inline-grid;
place-items: center;
}
/* Expand the hit area without touching layout or typography. */
.icon-button::after {
content: '';
position: absolute;
inset: 50%;
min-inline-size: 44px; /* Apple HIG floor; 48px for Material surfaces */
min-block-size: 44px;
translate: -50% -50%;
}
/* Focus Not Obscured, SC 2.4.11: reserve scroll space for sticky chrome. */
:root {
--sticky-header: 64px;
--sticky-footer: 56px;
--keyboard-inset: 0px;
}
html {
scroll-padding-block-start: calc(var(--sticky-header) + 8px);
scroll-padding-block-end: calc(var(--sticky-footer) + var(--keyboard-inset) + 8px);
}
/* Never remove the indicator; restyle it. */
:focus-visible {
outline: 3px solid #1a73e8;
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}// tests/a11y/keyboard.spec.ts — the gate that actually catches regressions.
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('address dialog is keyboard-complete and focus-trapped', async ({ page }) => {
await page.goto('/checkout');
const trigger = page.getByRole('button', { name: /edit shipping address/i });
await trigger.focus();
await page.keyboard.press('Enter');
const dialog = page.getByRole('dialog', { name: /shipping address/i });
await expect(dialog).toBeVisible();
// 25 tabs: focus must never escape, and must always be visibly scrolled into view.
for (let i = 0; i < 25; i++) {
await page.keyboard.press('Tab');
const escaped = await dialog.evaluate((el) => !el.contains(document.activeElement));
expect(escaped, 'focus escaped the dialog on tab ' + (i + 1)).toBe(false);
const obscured = await page.evaluate(() => {
const el = document.activeElement as HTMLElement;
const r = el.getBoundingClientRect();
const hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2);
return !hit || !(hit === el || el.contains(hit));
});
expect(obscured, 'focused element obscured on tab ' + (i + 1)).toBe(false); // SC 2.4.11
}
await page.keyboard.press('Escape');
await expect(dialog).toBeHidden();
await expect(trigger).toBeFocused(); // SC 2.4.3 Focus Order
// Static analysis is a floor, not a ceiling: it catches ~30-40% of real issues.
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa'])
.analyze();
expect(results.violations).toEqual([]);
});Performance Benchmarks & Trade-Offs
Representative numbers from a Chrome 124 / Apple M2 Pro profile: a dialog subtree with 500 focusable nodes, 2,000 focus moves driven through the CDP Input.dispatchKeyEvent path, medians and p95 reported per focus transition. Treat these as order-of-magnitude guidance — re-measure on your own DOM, because the cost is dominated by forced layout, not by your abstraction.
| Strategy | Trap LOC | Focus-move p50 / p95 | Focus-leak risk | Primary caveats | |---|---|---|---|---| | Native <dialog> + showModal() | ~0 trap / ~120 wrapper | 0.02 ms / 0.05 ms | Very low | Top layer + free inert-like isolation; ::backdrop styling constraints; scroll containment is awkward; needs a fallback path for Safari < 15.4 and non-modal use cases | | inert siblings + focusin guard | ~90 | 0.18 ms / 0.42 ms | Low | inert requires Chrome 102+/Safari 15.5+/FF 112+; must walk up to <body> or siblings above the portal stay tabbable | | Sentinel <span tabindex="0"> bookends | ~40 | 0.05 ms / 0.11 ms | Medium | Cheap and universal, but the SR virtual cursor still escapes; must be paired with a focusin guard anyway | | Manual keydown + querySelectorAll per press | ~150 | 1.4 ms / 2.6 ms | High | getBoundingClientRect/offsetParent per candidate forces layout; cost scales linearly with DOM size and multiplies under fast key repeat | | aria-activedescendant (no DOM focus moves) | ~60 | 0.03 ms / 0.07 ms | N/A (no trap needed) | Requires the full APG keyboard contract; unusable when the composite contains real text inputs; SR support varies by pairing |
Two trade-offs worth naming explicitly:
- `inert` vs `aria-hidden` + `tabindex` surgery.
inertis one attribute, reversible, and removes the subtree from hit-testing too. Manualtabindexsurgery on every descendant requires you to record and restore prior values — and any component that re-renders inside that subtree silently restores tabbability. - Native `<dialog>` vs portal.
<dialog>gives you the top layer and browser-managed trapping for free, but it also gives you opinionated centering,overflowbehavior, and a::backdropyou will fight. Design systems with heavy scroll-contained drawers usually land on a portal +inert, and pay the ~0.2 ms.
Pro-Tips & Common Pitfalls
- ❌
outline: nonewith no replacement. Non-negotiable. Use:focus-visiblewith ≥ 3:1 contrast against the adjacent background and ≥ 2 px perimeter. - ❌ Rendering a dialog into a portal and forgetting to
inertthe rest. React portals break the containment assumption that every hand-rolled trap relies on. - ❌ Re-mounting the live region on state change. Render it once at the app root; a conditionally rendered
<div aria-live>announces nothing. - ❌ Setting live-region text by mutating a child element instead of the region itself when
aria-atomic="false"— AT announces only the delta, which is often a single character. - ❌ Recomputing
tabindexon every keystroke in a roving-tabindex widget. Compute once per focus change; otherwise you thrash the accessibility tree and NVDA re-reads the label. - ❌ Expanding a target with
margin. The 24 px spacing exception counts the *gap between hit areas*; margins collapse and pseudo-element overlays do not. Use::after { position: absolute; inset: 50%; translate: -50% -50%; }. - ❌
tabindexvalues greater than 0. They hijack the entire document's tab order and are effectively unfixable once shipped. - ❌ Blocking paste on OTP, password, or email fields. That is a direct 3.3.8 failure — and a measurable conversion drop.
- ❌ Re-prompting for shipping data at payment. 3.3.7 Redundant Entry exists precisely for this; add an explicit 'same as shipping' control *and* prefill.
- ❌ Testing only in Chrome with axe. Your test matrix floor is: Safari + VoiceOver (iOS and macOS), Firefox + NVDA (Windows), Chrome + keyboard-only. Three pairings catch most divergent bugs.
- ❌ Treating an axe clean run as a sign-off. It flags roughly a third of real issues and reports most focus-order and live-region problems as *incomplete*.
- ✅ Ship a
<a href="#main">Skip to content</a>as the first focusable element, visible on focus, targeting atabindex="-1"main landmark. - ✅ Assert
toHaveAccessibleName()on every interactive component in the unit layer — it catches icon-button regressions before CI even boots a browser.
Frequently Asked Questions (FAQ)
Does WCAG 2.2 require `inert` or `aria-hidden` for modal dialogs?
No — the specification describes *outcomes*, not mechanisms. SC 2.4.3 (Focus Order) requires that focus order preserve meaning and operability; SC 1.3.1 requires that structure be programmatically determinable. A modal that leaves background content tabbable fails both, regardless of how you isolate it. inert is simply the cheapest correct mechanism today, because it removes a subtree from the tab order, hit-testing, *and* the accessibility tree in a single reversible attribute. aria-hidden alone is insufficient: it hides content from AT while leaving it fully focusable, which produces the classic 'focus disappears into nowhere' bug.
How do I stop an ARIA live region from double-announcing or not announcing in React?
Both symptoms share one cause: a mutation the AT did not observe. If the region node is created in the same render pass as its text, there is no diff to speak of — nothing is announced. If the same string is written twice, textContent assignment is a no-op and nothing is announced. The reliable pattern is: mount one persistent region at the app root with role="status" / aria-live="polite" and the sr-only clip class (never display: none); then for each announcement, clear textContent, wait two requestAnimationFrame callbacks, and write the message. Dedupe identical strings within a 1 s window and debounce source updates to 150–300 ms. Memoize the region component so React re-renders never replace the DOM node.
Is a 24×24 CSS px target enough, or do I need 44×44?
24×24 is the WCAG 2.2 SC 2.5.8 (AA) floor, and it comes with six exceptions — inline text links in a sentence, targets whose size is determined by the user agent, targets with an equivalent control elsewhere on the page, and targets spaced such that a 24 px-diameter circle centered on each does not intersect another. 44×44 is Apple's HIG minimum and 48×48 is Material's; neither is a WCAG requirement, but both are strong proxies for real touch accuracy on mobile. The pragmatic policy: 24×24 as the hard CI gate, 44×44 for primary touch actions on mobile surfaces, achieved by pseudo-element hit-area expansion so that layout and typography stay untouched.
