Skip to content
Derar Sattouf

Web Accessibility for Developers: WCAG 2.2, ARIA and Testing

Updated Next.js & frontend

Web Accessibility for Developers: WCAG 2.2, ARIA and Testing

Accessibility is a quality attribute of software, like performance or security. It's also a legal requirement in a growing number of markets, a measurable business advantage, and, most importantly, the difference between a person being able to use your product or not. The good news for developers is that most accessibility problems come from a small number of repeated mistakes, and most of them are cheaper to prevent in code review than to fix after launch.

Standards and laws move. Dates and thresholds below are as of late 2026, and anything likely to change is marked "verify". This is engineering guidance, not legal advice, and primary sources are linked in the sources section at the end.

Use semantic HTML first. A button is already focusable, keyboard operable and announced correctly, and most ARIA bugs come from rebuilding native elements with div. The first rule of ARIA is to not use ARIA if a native element or attribute does the job. Bad ARIA is worse than no ARIA, because it changes what assistive technology announces without changing behavior.

WCAG 2.2 (a W3C Recommendation since October 2023) is the current version. It adds nine success criteria, including Focus Not Obscured, Target Size (Minimum) of 24 by 24 CSS pixels, Dragging Movements, Consistent Help, Redundant Entry and Accessible Authentication, and it removes 4.1.1 Parsing. Level AA is the common legal and procurement target.

Everything must work with the keyboard alone: visible focus (:focus-visible), logical order, no traps, skip links, and managed focus for dialogs and route changes. Use the native dialog element with showModal() for modals; it provides focus containment, Escape handling and an inert background for free. In forms, every control has a programmatic label, errors are text associated with the field (aria-describedby), invalid fields get aria-invalid, and the error summary receives focus on submit. For contrast, aim for 4.5:1 for normal text and 3:1 for large text, UI boundaries, focus indicators and meaningful graphics. Never use color alone to convey meaning, and respect prefers-reduced-motion.

Automated tools (axe-core, Lighthouse, jsx-a11y) catch roughly a third to a half of issues by common estimates. They can't judge alt text quality, focus order sense, or screen reader experience, so you need manual keyboard and screen reader checks too. Put axe in unit tests, in Playwright end-to-end tests, and in CI as a gate that fails on new violations, and keep a baseline for legacy debt and ratchet it down. Test with at least one desktop screen reader per major platform you serve (VoiceOver on macOS/iOS, NVDA on Windows with Firefox or Chrome) and keyboard-only on every release.

Decision table: which approach for which problem

NeedPreferAvoidWhy
Clickable actionbuttondiv with onClickNative focus, Enter/Space, role
Navigationa with hrefbutton that calls router.pushOpen in new tab, correct role, prefetch
Modaldialog + showModal()Custom div plus hand-built focus trapBrowser handles inertness, Escape, focus return
Non-modal popuppopover attribute, or disclosure button with aria-expandedrole="menu" for plain link listsMenu role implies complex keyboard model
Site navigation menunav with a list of links, optional disclosure buttonsARIA menubarmenubar is for application menus
TabsTabs pattern (tablist, tab, tabpanel) only when content is truly switchable panelsTabs role for page navigationRoles promise specific keyboard behavior
Select with searchNative select, or combobox pattern with a listboxCustom div dropdownNative wins for mobile and AT
Form validationNative constraints plus visible error textPlaceholder-only hints, red border onlyPerceivable, programmatic
Icon buttonbutton with aria-label or visually hidden textIcon with title onlyReliable name
Hide visually onlyVisually-hidden utility classdisplay: nonedisplay: none removes it from AT
Hide from everyonehidden attribute or display: nonearia-hidden on focusable elementsFocusable hidden content is a trap
Live statusrole="status" or aria-live="polite" region present in DOM before updateInjecting a new live region with its messageMany screen readers miss it

The human reason

Roughly one in six people worldwide lives with a significant disability (World Health Organization estimate; verify the current figure). Disability includes permanent conditions (blindness, deafness, limited mobility), temporary ones (a broken arm), and situational ones (bright sunlight, a noisy train, one hand holding a baby). Keyboard operability, captions, readable contrast and clear errors help all of them.

This section is a high-level orientation. Laws change and apply differently by sector and size; consult counsel for a real compliance decision.

RegionLaw or standardWhat to know (verify current status)
European UnionEuropean Accessibility Act (Directive 2019/882), with the harmonized standard EN 301 549Requirements for many consumer products and services (e-commerce, banking services, e-books, passenger transport services, electronic communications) applied from 28 June 2025. Microenterprises providing services have an exemption. EN 301 549 references WCAG 2.1 AA for web content; updates may reference WCAG 2.2
EU public sectorWeb Accessibility Directive (2016/2102)Public sector websites and apps already must comply, with accessibility statements
United States, public entitiesADA Title II web rule (DOJ, 2024)Requires WCAG 2.1 Level AA for state and local government web content and apps. In April 2026 the DOJ issued an interim final rule extending compliance dates by one year: entities serving 50,000 or more people to 26 April 2027; smaller entities and special districts to a later date (reported as April 2028; verify)
United States, private sectorADA Title III as applied by courts, Section 508 for federalNo single technical rule in statute; lawsuits commonly cite WCAG 2.x AA. Section 508 incorporates WCAG 2.0 AA
CanadaAccessible Canada Act, AODA (Ontario)AODA requires WCAG 2.0 AA for many organizations
UKEquality Act 2010, Public Sector Bodies Accessibility RegulationsWCAG 2.2 AA is the target for public bodies after the regulations were updated; verify

The practical takeaway: WCAG 2.2 Level AA is the safe engineering target. It is a superset of 2.1 AA and 2.0 AA, so meeting it satisfies the technical references in all of the laws above.

The business reason

  • Reach and conversion. Checkout flows that work by keyboard and with screen readers convert more users. Poor form errors cost sales for everybody.
  • SEO overlap. Semantic headings, landmarks, link text and alt text are also what search engines and AI crawlers parse.
  • Maintainability. Native elements and token-based contrast produce less custom code to maintain.
  • Risk reduction. Remediation under a legal demand letter costs several times more than building correctly.
  • Procurement. Enterprise and public sector buyers ask for a VPAT or Accessibility Conformance Report based on WCAG.

POUR and the structure of WCAG

WCAG organizes requirements under four principles, remembered as POUR:

PrincipleMeaningDeveloper examples
PerceivableInformation can be perceived by at least one senseAlt text, captions, contrast, text resize, reflow, not color alone
OperableThe interface can be operated by diverse inputKeyboard, focus visible, enough time, no seizures, touch targets, pointer alternatives
UnderstandableContent and behavior are predictable and clearLanguage attribute, consistent navigation, input labels, error identification and suggestions
RobustWorks with current and future user agents and ATValid names, roles, states, values; status messages

Success criteria have three levels: A (minimum), AA (target for most laws), AAA (aspirational; not required in full for whole sites). The WCAG conformance model works per page, and a page conforms only if all of it does, including repeated components and third-party widgets.

What is new in WCAG 2.2

WCAG 2.2 became a W3C Recommendation on 5 October 2023 and was later published as an ISO standard (ISO/IEC 40500, verify the edition). It is backwards compatible: content that meets 2.2 also meets 2.1 and 2.0, except for 4.1.1 Parsing, which was removed because modern browsers handle parse errors uniformly.

The new success criteria

CriterionLevelWhat it requiresDeveloper action
2.4.11 Focus Not Obscured (Minimum)AAA focused element is not entirely hidden by author-created content such as sticky headers and cookie bannersUse scroll-padding-top for sticky headers; make banners dismissable and non-overlapping
2.4.12 Focus Not Obscured (Enhanced)AAANo part of the focused element is hiddenSame, stricter
2.4.13 Focus AppearanceAAAFocus indicator is large enough and has 3:1 contrast changeUse a 2px outline with offset and a contrasting color
2.5.7 Dragging MovementsAAAnything that can be dragged has a single-pointer alternativeAdd buttons or inputs for reorder, sliders with keyboard and clicking
2.5.8 Target Size (Minimum)AAPointer targets are at least 24 by 24 CSS pixels, with spacing exceptionsMinimum size-6, aim for 44 by 44 on touch
3.2.6 Consistent HelpAHelp mechanisms (contact, chat, FAQ link) appear in the same relative place across pagesPut help in the shared footer or header component
3.3.7 Redundant EntryAInformation already entered in a process is auto-populated or selectable, except where essentialDo not ask for shipping and billing address twice without offering reuse
3.3.8 Accessible Authentication (Minimum)AANo cognitive function test (memorizing, transcribing) is required to log in unless an alternative existsAllow paste in password fields, support password managers, passkeys, email links
3.3.9 Accessible Authentication (Enhanced)AAAStricter version with fewer exceptionsSame direction

What these mean in code

<!-- 3.3.8: allow password managers and paste -->
<label for="pw">Password</label>
<input id="pw" name="password" type="password" autocomplete="current-password" />

<!-- 3.3.7: let the user reuse data -->
<input type="checkbox" id="same" name="sameAsShipping" checked />
<label for="same">Billing address is the same as shipping</label>

<!-- 2.5.8: a compact icon button that still meets 24x24 -->
<button type="button" class="size-6 min-w-6 inline-grid place-items-center" aria-label="Close">
  <svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" /></svg>
</button>
/* 2.4.11: sticky header must not cover focused elements */
html { scroll-padding-top: 5rem; }
header.sticky { height: 4rem; }

/* 2.4.13-friendly focus indicator */
:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
  outline: 3px solid var(--focus, #1d4ed8);
  outline-offset: 2px;
}

Semantic HTML first

Why it wins

Browsers expose each native element to assistive technology through the accessibility tree with a role, name, state and value. A native button gives you: focusability, Enter and Space activation, a role, disabled semantics, form participation and platform styling in forced-colors mode. Rebuilding that with a div requires at least five attributes and handlers, and every omission is a bug.

<!-- Bad: no role, not focusable, no keyboard -->
<div class="btn" onclick="save()">Save</div>

<!-- Bad but common: div made to look native -->
<div class="btn" role="button" tabindex="0" onclick="save()" onkeydown="if (event.key === 'Enter') save()">Save</div>
<!-- Still wrong: Space does not work, no disabled state, no form submit -->

<!-- Good -->
<button type="button" onclick="save()">Save</button>

Landmarks and structure

Every page should have one main, a header, nav for navigation (labelled if there are several), and a footer. Headings form an outline: one h1, then h2 and so on without skipping levels for visual size. Lists should be real lists.

<body>
  <a class="skip-link" href="#main">Skip to main content</a>
  <header>
    <nav aria-label="Primary">
      <ul>
        <li><a href="/" aria-current="page">Home</a></li>
        <li><a href="/pricing">Pricing</a></li>
      </ul>
    </nav>
  </header>
  <main id="main" tabindex="-1">
    <h1>Pricing</h1>
    <section aria-labelledby="plans-h">
      <h2 id="plans-h">Plans</h2>
    </section>
  </main>
  <footer><nav aria-label="Footer">...</nav></footer>
</body>

Set the document language (html lang="en") so screen readers pick the right voice, and mark language changes inline with lang on the element.

If it...Use
Goes to a URLa href
Changes something on the current page (submit, open, toggle)button
Looks like a link but acts like a buttonStill a button, styled
Is a link without a real URL (href="#")Fix the design: it is a button

Link text must make sense out of context, because screen reader users navigate by a list of links. Avoid "click here" and "read more" without context; add visually hidden text or aria-label that includes the subject.

<a href="/blog/wcag-2-2">Read more<span class="sr-only"> about WCAG 2.2 changes</span></a>
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}

ARIA: rules, roles and when NOT to use it

ARIA (Accessible Rich Internet Applications) is a set of attributes that supplement the accessibility tree when HTML cannot express a widget. It changes what is announced; it does not add behavior.

The five rules of ARIA (paraphrased from the W3C)

  1. If a native element or attribute has the semantics and behavior you need, use it instead of repurposing an element and adding ARIA.
  2. Do not change native semantics unless you really have to (for example, do not put role="heading" on a button).
  3. All interactive ARIA controls must be keyboard operable.
  4. Do not use role="presentation" or aria-hidden="true" on a focusable element.
  5. All interactive elements must have an accessible name.

Names, roles, states

Every control needs a name (what it is), a role (what kind it is) and state or value (its current condition). Names come, in priority order, from aria-labelledby, then aria-label, then native sources (label, alt, text content, legend), then title as a last resort.

AttributePurposeExample
aria-labelName directlyIcon-only button
aria-labelledbyName from another element's textDialog title
aria-describedbyExtra descriptionField hint and error text
aria-expandedDisclosure open or closedMenu button, accordion
aria-controlsRelationship (support is uneven; do not rely on it)Button to panel
aria-currentCurrent item in a setActive nav link: page, step
aria-pressedToggle button stateBold button
aria-selectedSelected item in tabs, listboxActive tab
aria-checkedCheckbox-like rolesCustom switch
aria-invalidField has an errorForm input
aria-requiredRequired field (native required is preferred)Custom controls
aria-liveAnnounce changesStatus messages
aria-hiddenRemove from accessibility treeDecorative icons
aria-modalDialog makes the rest inert (native dialog does this)Custom dialogs
aria-busyRegion is updatingLoading lists

The "no ARIA is better than bad ARIA" examples

<!-- Redundant: native role already button -->
<button role="button">Save</button>

<!-- Harmful: overrides link semantics -->
<a href="/settings" role="button">Settings</a>

<!-- Harmful: tabs role for navigation promises arrow key behavior that is not built -->
<ul role="tablist"><li role="tab"><a href="/a">A</a></li></ul>

<!-- Harmful: hides focusable content from AT while keyboard users can still tab to it -->
<div aria-hidden="true"><button>Buy</button></div>

<!-- Harmful: aria-label on a div or span with no role is ignored by many AT -->
<div aria-label="Product price">$49</div>

When ARIA is the right tool

  • Custom widgets with no HTML equivalent: tabs, combobox with a listbox popup, tree, menu (application style), tooltip.
  • Dynamic announcements: live regions for toasts, form results, loading states.
  • Labelling and relationships: aria-labelledby, aria-describedby.
  • State on native elements: aria-expanded on a disclosure button, aria-current on the active link, aria-pressed on toggles.

The "ARIA Authoring Practices" patterns

The WAI-ARIA Authoring Practices Guide (APG) defines the expected keyboard interactions for each widget role. If you use a role, you must implement its keyboard model, otherwise you are lying to screen reader users. When possible, use a headless library that implements these (Radix Primitives, React Aria, Base UI, Headless UI, Ark UI) rather than hand-rolling combobox and menu.

Live regions done right

A live region must exist in the DOM before its content changes. Announce results of actions that do not move focus: "3 results found", "Saved", "Item added to cart".

<div role="status" aria-live="polite" id="status" class="sr-only"></div>

<script>
  function announce(message) {
    const el = document.getElementById("status");
    el.textContent = "";
    // a microtask delay helps some screen readers notice a repeat message
    setTimeout(() => { el.textContent = message; }, 50);
  }
</script>

Use role="alert" (assertive) only for urgent, interrupting messages such as errors that block a task. Do not use live regions for large content updates; move focus to the new content instead.

Keyboard and focus management

The baseline contract

Everything you can do with a mouse must be possible with a keyboard, and the user must always see where focus is.

KeyExpected behavior
Tab / Shift+TabMove between interactive elements in DOM order
EnterActivate links and buttons; submit forms
SpaceActivate buttons; toggle checkboxes; scroll the page
Arrow keysMove within a composite widget (tabs, menu, listbox, radio group)
EscapeClose the topmost popup, dialog or menu; return focus to the trigger
Home / EndFirst or last item in a composite widget

Focus order and tabindex

  • Keep DOM order equal to visual order. Do not reorder visually with CSS order or absolute positioning in ways that break tab order (WCAG 2.4.3 and 1.3.2).
  • tabindex="0" adds an element to the tab order. Use it only on custom widgets that follow a pattern.
  • tabindex="-1" makes an element focusable by script but not by Tab. Use it for focus targets such as main or headings.
  • Never use positive tabindex values.

Visible focus with :focus-visible

:focus-visible shows the outline for keyboard use and hides it for mouse clicks on most elements. Never remove the outline without a replacement.

:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
  outline: 3px solid #1d4ed8;
  outline-offset: 2px;
  border-radius: 2px;
}

/* On dark surfaces use a token that contrasts there */
.dark :where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
  outline-color: #93c5fd;
}

A skip link is the first focusable element and jumps past repeated navigation (WCAG 2.4.1 Bypass Blocks).

.skip-link {
  position: absolute;
  left: 0.5rem;
  top: -4rem;
  padding: 0.75rem 1rem;
  background: #fff;
  color: #000;
  z-index: 1000;
}
.skip-link:focus { top: 0.5rem; }

The target must receive focus. main needs tabindex="-1" for the focus move to work in all browsers.

Roving tabindex for composite widgets

In a toolbar, tablist, radio group or menu, only one item is in the tab order at a time and the arrow keys move between items. This makes the whole widget one tab stop.

// useRovingFocus.tsx
import { useRef, useState, type KeyboardEvent } from "react";

export function useRovingFocus(count: number, orientation: "horizontal" | "vertical" = "horizontal") {
  const [active, setActive] = useState(0);
  const refs = useRef<Array<HTMLElement | null>>([]);

  const focusIndex = (index: number) => {
    const next = (index + count) % count;
    setActive(next);
    refs.current[next]?.focus();
  };

  const onKeyDown = (event: KeyboardEvent) => {
    const prev = orientation === "horizontal" ? "ArrowLeft" : "ArrowUp";
    const next = orientation === "horizontal" ? "ArrowRight" : "ArrowDown";
    if (event.key === next) { event.preventDefault(); focusIndex(active + 1); }
    else if (event.key === prev) { event.preventDefault(); focusIndex(active - 1); }
    else if (event.key === "Home") { event.preventDefault(); focusIndex(0); }
    else if (event.key === "End") { event.preventDefault(); focusIndex(count - 1); }
  };

  const getItemProps = (index: number) => ({
    ref: (el: HTMLElement | null) => { refs.current[index] = el; },
    tabIndex: index === active ? 0 : -1,
    onFocus: () => setActive(index),
  });

  return { onKeyDown, getItemProps };
}

An alternative for simple cases is aria-activedescendant, where DOM focus stays on a container (used by comboboxes) and the attribute points at the visually active option.

Focus traps: do them only where needed

A focus trap keeps Tab within a modal. In 2026 you rarely need to build one: the native dialog element opened with showModal() makes the rest of the page inert. If you must support a custom overlay, use the inert attribute on the rest of the page instead of intercepting Tab:

// Mark everything except the modal as inert while it is open
useEffect(() => {
  const app = document.getElementById("app-root");
  if (!app) return;
  app.inert = open;
  return () => { app.inert = false; };
}, [open]);

Never trap focus in non-modal content: WCAG 2.1.2 No Keyboard Trap requires that a user can always leave with standard keys.

Managing focus in single page apps

On client-side route changes, browsers do not move focus or announce a new page. Do both: update document.title, and move focus to the main heading or container, or use a polite live region announcing the new page title.

// RouteAnnouncer.tsx (framework-agnostic idea; Next.js includes its own announcer)
import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";

export function RouteFocus() {
  const pathname = usePathname();
  const first = useRef(true);

  useEffect(() => {
    if (first.current) { first.current = false; return; }
    const h1 = document.querySelector("h1");
    if (h1) {
      h1.setAttribute("tabindex", "-1");
      (h1 as HTMLElement).focus({ preventScroll: false });
    }
  }, [pathname]);

  return null;
}

Next.js includes a built-in route announcer that reads the page title (the next-route-announcer element), so make sure each route sets a unique title via metadata. Verify behavior for your framework version.

Returning focus

When a dialog, popover or menu closes, return focus to the element that opened it. When an item is deleted from a list, move focus to the next item or the list heading rather than letting focus fall back to body.

Accessible forms

Labels

Every input needs a visible, programmatically associated label. Placeholders are hints, not labels: they vanish when typing and often fail contrast.

<div class="field">
  <label for="email">Email address</label>
  <input id="email" name="email" type="email" autocomplete="email" required
         aria-describedby="email-hint email-error" aria-invalid="false" />
  <p id="email-hint" class="hint">We will send your receipt here.</p>
  <p id="email-error" class="error" hidden></p>
</div>

Groups

Related controls (radio buttons, checkboxes) go in a fieldset with a legend:

<fieldset>
  <legend>Notification preferences</legend>
  <label><input type="checkbox" name="n" value="email" /> Email</label>
  <label><input type="checkbox" name="n" value="sms" /> SMS</label>
</fieldset>

Autocomplete and input types

Use the autocomplete attribute with standard tokens (name, email, tel, street-address, postal-code, cc-number, one-time-code, current-password, new-password) to satisfy WCAG 1.3.5 Identify Input Purpose and help users with motor or cognitive disabilities. Use the correct type (email, tel, url, number where appropriate; for IDs and zip codes use inputmode="numeric" with type="text").

Errors: the full pattern

A good error pattern has four parts:

  1. Validate on submit (and on blur after the first error), not on every keystroke.
  2. Show a clear text message next to the field that says what is wrong and how to fix it. Do not rely on color or an icon alone.
  3. Associate the message with the field (aria-describedby) and set aria-invalid="true".
  4. On submit with errors, move focus to an error summary at the top, or to the first invalid field, and make the summary links jump to each field.
// SignupForm.tsx
"use client";
import { useRef, useState, type FormEvent } from "react";

type Errors = Partial<Record<"email" | "password", string>>;

export function SignupForm() {
  const [errors, setErrors] = useState<Errors>({});
  const summaryRef = useRef<HTMLDivElement>(null);

  function validate(form: FormData): Errors {
    const next: Errors = {};
    const email = String(form.get("email") ?? "");
    const password = String(form.get("password") ?? "");
    if (!/^\S+@\S+\.\S+$/.test(email)) next.email = "Enter an email address like name@example.com.";
    if (password.length < 12) next.password = "Use at least 12 characters. A passphrase works well.";
    return next;
  }

  function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const next = validate(new FormData(event.currentTarget));
    setErrors(next);
    if (Object.keys(next).length > 0) {
      // wait for the summary to render, then move focus
      requestAnimationFrame(() => summaryRef.current?.focus());
    }
  }

  const entries = Object.entries(errors) as Array<[keyof Errors, string]>;

  return (
    <form onSubmit={onSubmit} noValidate>
      {entries.length > 0 && (
        <div ref={summaryRef} tabIndex={-1} role="alert" className="error-summary">
          <h2>There is a problem</h2>
          <ul>
            {entries.map(([name, message]) => (
              <li key={name}><a href={`#${name}`}>{message}</a></li>
            ))}
          </ul>
        </div>
      )}

      <div className="field">
        <label htmlFor="email">Email address</label>
        <input
          id="email" name="email" type="email" autoComplete="email"
          aria-invalid={errors.email ? true : undefined}
          aria-describedby={errors.email ? "email-error" : undefined}
        />
        {errors.email && <p id="email-error" className="error">Error: {errors.email}</p>}
      </div>

      <div className="field">
        <label htmlFor="password">Password</label>
        <input
          id="password" name="password" type="password" autoComplete="new-password"
          aria-invalid={errors.password ? true : undefined}
          aria-describedby={errors.password ? "password-error" : undefined}
        />
        {errors.password && <p id="password-error" className="error">Error: {errors.password}</p>}
      </div>

      <button type="submit">Create account</button>
    </form>
  );
}

The in-page anchors #email and #password work because each input has that id. React 19 form actions integrate with this; see React 19 in Practice for useActionState driven validation, and apply the same markup.

Required fields and instructions

State required fields in the label text ("Email (required)") or explain the convention once at the top. Keep the native required attribute, which also exposes the required state to assistive technology, and use noValidate on the form only if you replace the browser validation bubbles with your own error pattern.

Do not disable the submit button as validation

A disabled submit button gives no explanation and is skipped by keyboard users. Leave it enabled, validate on submit and explain. Use a disabled state only for in-flight submissions, and announce progress ("Saving...").

Timeouts and redundant entry

Warn before a session timeout and allow extension (WCAG 2.2.1). Preserve form data after errors, and avoid asking for the same information twice (WCAG 3.3.7).

Dialogs and modals

<button type="button" id="open">Delete project</button>

<dialog id="confirm" aria-labelledby="confirm-title" aria-describedby="confirm-desc">
  <form method="dialog">
    <h2 id="confirm-title">Delete project?</h2>
    <p id="confirm-desc">This permanently removes all files. This cannot be undone.</p>
    <button value="cancel" autofocus>Cancel</button>
    <button value="confirm">Delete</button>
  </form>
</dialog>

<script>
  const dialog = document.getElementById("confirm");
  const opener = document.getElementById("open");
  opener.addEventListener("click", () => dialog.showModal());
  dialog.addEventListener("close", () => {
    if (dialog.returnValue === "confirm") deleteProject();
    opener.focus(); // browsers usually restore focus; being explicit is harmless
  });
</script>

What showModal() gives you: the dialog is placed in the top layer, content outside is inert (not focusable, not exposed to AT), Escape closes it, a ::backdrop pseudo-element appears, and focus moves into the dialog (to the autofocus element if present, otherwise the first focusable element). Put autofocus on the least destructive action for confirmations.

dialog {
  border: 1px solid var(--border);
  border-radius: 0.75rem;
  padding: 1.5rem;
  max-width: min(32rem, calc(100vw - 2rem));
}
dialog::backdrop { background: oklch(0 0 0 / 0.5); }

React wrapper

// Modal.tsx
import { useEffect, useRef, type ReactNode } from "react";

type ModalProps = {
  open: boolean;
  onClose: () => void;
  title: string;
  children: ReactNode;
};

export function Modal({ open, onClose, title, children }: ModalProps) {
  const ref = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const dialog = ref.current;
    if (!dialog) return;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);

  return (
    <dialog ref={ref} aria-labelledby="modal-title" onClose={onClose}>
      <h2 id="modal-title">{title}</h2>
      {children}
      <button type="button" onClick={() => ref.current?.close()}>Close</button>
    </dialog>
  );
}

React 19 treats ref as a regular prop and supports onClose on dialog. The native close event fires for Escape as well, so state stays in sync. For multiple dialogs on one page, generate unique ids with useId.

Dialog checklist

  • Has an accessible name (heading plus aria-labelledby).
  • Opens with showModal() for modal behavior; focus lands inside.
  • Escape closes it; there is a visible close or cancel button.
  • Focus returns to the opener on close.
  • Page behind does not scroll (body:has(dialog[open]) { overflow: hidden; }).
  • Not used for content that should be a page (long forms, complex flows).
  • Alert dialogs (role="alertdialog") for confirmations needing a response.

Popovers and tooltips

The popover attribute provides light-dismiss, top layer rendering and keyboard handling for non-modal overlays:

<button type="button" popovertarget="help" aria-describedby="help">Help</button>
<div id="help" popover>
  Passwords must be at least 12 characters.
</div>

For tooltips, content must be reachable by keyboard focus as well as hover, dismissible with Escape, and hoverable without disappearing (WCAG 1.4.13 Content on Hover or Focus). Do not put interactive content in a tooltip; use a popover or dialog.

Disclosure navigation (what most sites need)

A site navigation menu with submenus is not an ARIA menu. Use a button with aria-expanded that toggles a list of links:

<nav aria-label="Primary">
  <ul>
    <li>
      <button type="button" aria-expanded="false" aria-controls="products-menu">Products</button>
      <ul id="products-menu" hidden>
        <li><a href="/products/a">Product A</a></li>
        <li><a href="/products/b">Product B</a></li>
      </ul>
    </li>
    <li><a href="/pricing">Pricing</a></li>
  </ul>
</nav>
// DisclosureNav.tsx
import { useEffect, useRef, useState, useId } from "react";

export function DisclosureItem({ label, children }: { label: string; children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const id = useId();
  const root = useRef<HTMLLIElement>(null);
  const button = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") { setOpen(false); button.current?.focus(); }
    };
    const onFocusOut = (e: FocusEvent) => {
      if (root.current && !root.current.contains(e.relatedTarget as Node | null)) setOpen(false);
    };
    const node = root.current;
    document.addEventListener("keydown", onKey);
    node?.addEventListener("focusout", onFocusOut);
    return () => {
      document.removeEventListener("keydown", onKey);
      node?.removeEventListener("focusout", onFocusOut);
    };
  }, [open]);

  return (
    <li ref={root}>
      <button ref={button} type="button" aria-expanded={open} aria-controls={id} onClick={() => setOpen(o => !o)}>
        {label}
      </button>
      <ul id={id} hidden={!open}>{children}</ul>
    </li>
  );
}

ARIA menu button (application-style menus)

Use role="menu" only for action menus like an editor's "File" menu, where items perform commands. The keyboard model is: Enter, Space or Down opens the menu and focuses the first item; Up and Down move; Home and End jump; Escape closes and returns focus; Tab closes the menu; typing a character focuses the next item starting with it. That is a lot of behavior; use Radix DropdownMenu, React Aria Menu or Base UI instead of writing it.

<nav aria-label="Breadcrumb">
  <ol>
    <li><a href="/">Home</a></li>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/blog/a11y" aria-current="page">Accessibility</a></li>
  </ol>
</nav>

Tabs

Use the tabs pattern when you switch between panels of related content on one page. The roles and keyboard model: one tab stop on the tablist (the selected tab), Left and Right arrows move between tabs, Home and End jump, and the tabpanel is the next tab stop after the tablist.

// Tabs.tsx
import { useId, useRef, useState, type KeyboardEvent } from "react";

type Tab = { id: string; label: string; content: React.ReactNode };

export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) {
  const [selected, setSelected] = useState(0);
  const base = useId();
  const refs = useRef<Array<HTMLButtonElement | null>>([]);

  const move = (index: number) => {
    const next = (index + tabs.length) % tabs.length;
    setSelected(next);
    refs.current[next]?.focus();
  };

  const onKeyDown = (event: KeyboardEvent) => {
    switch (event.key) {
      case "ArrowRight": event.preventDefault(); move(selected + 1); break;
      case "ArrowLeft": event.preventDefault(); move(selected - 1); break;
      case "Home": event.preventDefault(); move(0); break;
      case "End": event.preventDefault(); move(tabs.length - 1); break;
    }
  };

  return (
    <div>
      <div role="tablist" aria-label={label} onKeyDown={onKeyDown}>
        {tabs.map((tab, i) => (
          <button
            key={tab.id}
            ref={(el) => { refs.current[i] = el; }}
            role="tab"
            type="button"
            id={`${base}-tab-${tab.id}`}
            aria-selected={selected === i}
            aria-controls={`${base}-panel-${tab.id}`}
            tabIndex={selected === i ? 0 : -1}
            onClick={() => setSelected(i)}
          >
            {tab.label}
          </button>
        ))}
      </div>
      {tabs.map((tab, i) => (
        <div
          key={tab.id}
          role="tabpanel"
          id={`${base}-panel-${tab.id}`}
          aria-labelledby={`${base}-tab-${tab.id}`}
          hidden={selected !== i}
          tabIndex={0}
        >
          {tab.content}
        </div>
      ))}
    </div>
  );
}

This version uses automatic activation (selection follows focus), appropriate when panels render instantly. If switching is expensive, use manual activation: arrows move focus only, Enter or Space selects.

When not to use tabs: for site navigation, for long linear content users must read in order, or for something with a single panel. Use links, headings or an accordion built from details and summary:

<details>
  <summary>Shipping information</summary>
  <p>Orders ship within two business days.</p>
</details>

Combobox, autocomplete and select

Prefer native

A native select is accessible, works on every platform and has a great mobile picker. Use it unless you need search, multi-select with tags or rich options. An input with a datalist is an acceptable low-effort autocomplete, with inconsistent styling and screen reader behavior across browsers (test it).

The combobox pattern (editable, list autocomplete)

The ARIA 1.2 combobox: a text input with role="combobox", aria-expanded, aria-controls pointing at a listbox, and aria-activedescendant pointing at the highlighted option. DOM focus stays in the input while arrow keys change the active descendant.

KeyBehavior
Down ArrowOpen list if closed; move to next option
Up ArrowMove to previous option (or open and move to last)
EnterSelect the active option; close list
EscapeClose list; second press clears the input (optional)
Home / EndMove caret in the input (do not hijack)
TypingFilter options; keep focus in the input
// Combobox.tsx
import { useId, useMemo, useState, type KeyboardEvent } from "react";

export function Combobox({ label, options, onSelect }: {
  label: string;
  options: string[];
  onSelect: (value: string) => void;
}) {
  const id = useId();
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(-1);

  const filtered = useMemo(
    () => options.filter((o) => o.toLowerCase().includes(query.toLowerCase())),
    [options, query],
  );

  const listId = `${id}-list`;
  const optionId = (i: number) => `${id}-opt-${i}`;

  function commit(value: string) {
    setQuery(value);
    setOpen(false);
    setActive(-1);
    onSelect(value);
  }

  function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setOpen(true);
      setActive((a) => Math.min(a + 1, filtered.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActive((a) => Math.max(a - 1, 0));
    } else if (e.key === "Enter" && open && active >= 0) {
      e.preventDefault();
      commit(filtered[active]);
    } else if (e.key === "Escape") {
      setOpen(false);
      setActive(-1);
    }
  }

  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input
        id={id}
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={open}
        aria-controls={listId}
        aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
        value={query}
        onChange={(e) => { setQuery(e.target.value); setOpen(true); setActive(-1); }}
        onKeyDown={onKeyDown}
        onBlur={() => setOpen(false)}
        autoComplete="off"
      />
      <ul id={listId} role="listbox" aria-label={label} hidden={!open}>
        {filtered.map((option, i) => (
          <li
            key={option}
            id={optionId(i)}
            role="option"
            aria-selected={i === active}
            onMouseDown={(e) => { e.preventDefault(); commit(option); }}
          >
            {option}
          </li>
        ))}
      </ul>
      <div role="status" aria-live="polite" className="sr-only">
        {open ? `${filtered.length} results available` : ""}
      </div>
    </div>
  );
}

The onMouseDown with preventDefault stops the input losing focus before the click registers, a classic combobox bug. The status region announces the result count.

The cost is real: a combobox you can ship also needs touch behavior, virtualization for large lists, grouping, async loading and IME composition handling. In production, use React Aria ComboBox, Radix-based cmdk/shadcn Combobox, or Downshift, and test them with real screen readers.

Color, contrast, motion and sensory characteristics

Contrast

ElementRatio (WCAG)
Body text4.5:1 (1.4.3 AA)
Large text (at least 24px regular or 18.66px bold)3:1
Input borders, icons that carry meaning, focus rings, chart elements3:1 against adjacent colors (1.4.11 AA)
Disabled controls and pure decorationExempt
LogosExempt

Check both themes. Disabled-looking text that is actually active (muted gray helper text) is a frequent failure. If you use design tokens, test pairs in CI (see Tailwind CSS v4: Migration Guide, CSS-First Config and Design Tokens That Scale). Note that WCAG 3 drafts propose a different algorithm (APCA); WCAG 2.x contrast ratios remain the legal measure.

Do not rely on color alone

Add a second cue: icon plus text for errors, underline for inline links, patterns or labels in charts, shape differences for status dots.

<p class="error"><svg aria-hidden="true" width="16" height="16"><!-- icon --></svg> Error: Enter a valid date.</p>

Text resize and reflow

  • Layouts must work at 200% text zoom (1.4.4) and reflow at 320 CSS pixels width without horizontal scrolling (1.4.10). Use relative units (rem, em), min-width: 0 in flex and grid children, and avoid fixed heights on text containers.
  • Support text spacing overrides (1.4.12): content must not clip when a user sets line height to 1.5, paragraph spacing to 2 times, letter spacing 0.12em, word spacing 0.16em.
  • Do not disable pinch zoom: no user-scalable=no or maximum-scale=1.

Motion

Provide a reduced-motion path for parallax, large transitions, auto-playing animation and scroll-jacking:

@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

Anything that moves, blinks or scrolls automatically for more than five seconds needs a pause, stop or hide control (2.2.2). Nothing may flash more than three times per second (2.3.1).

// Reading the preference in React
import { useSyncExternalStore } from "react";

const query = "(prefers-reduced-motion: reduce)";
function subscribe(cb: () => void) {
  const mq = window.matchMedia(query);
  mq.addEventListener("change", cb);
  return () => mq.removeEventListener("change", cb);
}
export function usePrefersReducedMotion() {
  return useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);
}

Forced colors and dark mode

Windows High Contrast (forced colors) overrides your palette. Use system colors for custom controls (CanvasText, Highlight), avoid conveying state by background color alone, and test with forced-colors emulation in browser DevTools. Use color-scheme so native controls match the theme.

Images, media and icons

Alt text decision tree

Image typeAlt text
Informative (photo conveying content)Short description of the content and purpose
Functional (icon inside a button or link)Describe the action, not the picture: "Search", "Download report (PDF)"
DecorativeEmpty alt: alt="" so AT skips it
Complex (chart, diagram)Short alt that states the takeaway, plus a longer description or data table nearby
Text in an imageSame text as in the image (avoid text in images)
Logo linking home"Company name, home"
<img src="/chart.png" alt="Revenue grew 40 percent from Q1 to Q4 2026" />
<p><a href="#chart-data">View chart data as a table</a></p>

<button type="button"><svg aria-hidden="true" focusable="false">...</svg><span class="sr-only">Delete comment</span></button>

SVG

Decorative inline SVG gets aria-hidden="true" and focusable="false". Standalone meaningful SVG gets role="img" and a title or aria-label.

Video and audio

Provide captions for prerecorded video (1.2.2 A), audio description or a transcript for visual-only information (1.2.3, 1.2.5 AA), transcripts for audio, and no autoplay with sound. Use native video with track elements:

<video controls preload="metadata" poster="/poster.jpg">
  <source src="/demo.mp4" type="video/mp4" />
  <track kind="captions" src="/demo.en.vtt" srclang="en" label="English" default />
</video>

AI-generated alt text

Automated alt text suggestions are a useful first draft and a poor final answer: models do not know the purpose of the image on your page. Require human review, and prefer empty alt for decorative imagery.

Screen reader testing workflow

Automation cannot tell you whether the experience makes sense. Plan short, regular manual sessions.

Which screen readers and browsers

PlatformScreen readerTypical browser pairing
macOSVoiceOver (built in)Safari
iOSVoiceOverSafari
WindowsNVDA (free)Firefox or Chrome
WindowsJAWS (commercial; common in enterprise)Chrome, Edge
AndroidTalkBackChrome

If your analytics or customers dictate it, add JAWS. For small teams, VoiceOver plus NVDA covers most issues.

VoiceOver quick start (macOS)

ActionShortcut
Start or stop VoiceOverCmd+F5
VoiceOver modifier ("VO")Control+Option
Rotor (lists of headings, links, landmarks, form controls)VO+U
Next or previous itemVO+Right or VO+Left
ActivateVO+Space
Read from hereVO+A
Quick Nav togglingLeft+Right arrow together

In Safari, enable "Press Tab to highlight each item on a webpage" in settings, otherwise Tab skips links and the experience differs from other browsers (verify the exact setting name in your macOS version).

NVDA quick start (Windows)

ActionShortcut
NVDA modifierInsert (or Caps Lock)
Stop speechControl
Headings list / links list / landmarksNVDA+F7 for elements list; single keys H, K, D in browse mode
Next heading, link, form field, landmarkH, K, F, D
Browse mode versus focus modeNVDA+Space
Read allNVDA+Down Arrow

The five-minute smoke test per feature

  1. Navigate by headings (H or the rotor). Does the outline describe the page?
  2. Navigate by landmarks. Are main, nav, header, footer present and labelled?
  3. List all links and buttons. Are names unique and meaningful out of context?
  4. Tab through interactive elements with the screen reader on. Does each announce name, role and state?
  5. Complete the primary task (search, add to cart, submit form) using only the keyboard and speech. Trigger errors deliberately. Are errors announced, and does focus go somewhere sensible?
  6. Open and close the dialog and menu. Is focus moved in, trapped or inert behind, and returned?
  7. Check dynamic updates: toasts, loading states, live search results.

Record what you heard, not just pass or fail. Create issues with the screen reader, browser and version.

Keyboard-only and zoom tests

  • Unplug the mouse (or just do not touch it) and complete the main flow. Look for lost focus, hidden focus indicators, unreachable controls and traps.
  • Zoom to 200 percent and 400 percent (320 px reflow). Check clipped text and horizontal scroll.
  • Emulate prefers-reduced-motion, forced-colors and dark mode in DevTools rendering panel.
  • Use browser DevTools Accessibility pane to inspect the accessibility tree: name, role, states.

Voice control and switch access

Name-in-label (2.5.3 Label in Name): the accessible name must contain the visible label text so voice control users can say "click Search". An aria-label="Find products" on a button that visibly says "Search" breaks that.

Automated testing

What automation can and cannot do

Static and dynamic tools detect objective rule violations: missing alt, missing labels, invalid ARIA, low contrast (when the colors are computable), duplicate ids in specific cases, missing page language, empty buttons and links, heading structure problems. Studies of rule coverage typically conclude that automated tools find a minority to about half of the WCAG issues present on a page (figures vary by study and by method; treat any number as an approximation).

Detected wellNot detected (needs a human)
Missing or empty accessible namesWhether the name is meaningful
Missing altWhether the alt text is accurate and appropriate
Insufficient contrast on solid backgroundsContrast on images and gradients, hover and focus states not rendered
Invalid or misused ARIA attributesWhether the widget's keyboard behavior matches its role
Missing form labelsWhether the error messages are helpful
Missing language, title, landmark rulesLogical reading and focus order
Some target-size rulesCognitive load, plain language, consistent help
Duplicate landmarks or idsScreen reader announcements and live region timing
Missing captions track elementCaption accuracy and audio description quality

eslint-plugin-jsx-a11y

Static checks while coding. In a flat config:

// eslint.config.mjs
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import jsxA11y from "eslint-plugin-jsx-a11y";

export default [
  js.configs.recommended,
  ...tseslint.configs.recommended,
  jsxA11y.flatConfigs.recommended,
  {
    rules: {
      "jsx-a11y/no-autofocus": "off", // allow autofocus inside dialogs; review manually
      "jsx-a11y/anchor-is-valid": ["error", { aspects: ["invalidHref", "preferButton"] }],
    },
  },
];

Next.js's eslint-config-next ships a subset of jsx-a11y rules; the full plugin adds more. Custom components break static analysis (a Button component rendered as div); configure the components setting to map custom components to elements if needed. Verify the flat-config export name in the plugin's README for your version.

axe-core in unit and component tests (jest-axe)

// button.a11y.test.tsx
import { render } from "@testing-library/react";
import { axe, toHaveNoViolations } from "jest-axe";
import { SignupForm } from "./SignupForm";

expect.extend(toHaveNoViolations);

test("SignupForm has no detectable accessibility violations", async () => {
  const { container } = render(<SignupForm />);
  expect(await axe(container)).toHaveNoViolations();
});

For Vitest, use vitest-axe (same API with expect.extend) or call axe-core directly. jsdom has no layout, so contrast and visibility rules are unreliable in unit tests; run those rules in a real browser. Treat unit-level axe as a cheap catch for names, roles, labels and ARIA validity. See Unit Testing with AI in 2026 for general test structure.

Test behavior too, not just rules. Keyboard behavior is testable with Testing Library:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Tabs } from "./Tabs";

test("arrow keys move between tabs and update selection", async () => {
  const user = userEvent.setup();
  render(<Tabs label="Settings" tabs={[
    { id: "a", label: "Profile", content: "Profile panel" },
    { id: "b", label: "Billing", content: "Billing panel" },
  ]} />);

  await user.tab();
  expect(screen.getByRole("tab", { name: "Profile" })).toHaveFocus();
  await user.keyboard("{ArrowRight}");
  expect(screen.getByRole("tab", { name: "Billing" })).toHaveFocus();
  expect(screen.getByRole("tab", { name: "Billing" })).toHaveAttribute("aria-selected", "true");
  expect(screen.getByRole("tabpanel", { name: "Billing" })).toBeVisible();
});

Using getByRole with a name is itself an accessibility test: if the query fails, assistive technology probably cannot find the element either.

Playwright with axe

Run axe in a real browser against real pages. Install @axe-core/playwright.

// e2e/a11y.spec.ts
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

const pages = ["/", "/pricing", "/blog", "/contact"];

for (const path of pages) {
  test(`no WCAG A/AA violations on ${path}`, async ({ page }) => {
    await page.goto(path);
    await page.waitForLoadState("networkidle");

    const results = await new AxeBuilder({ page })
      .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"])
      .analyze();

    expect(results.violations).toEqual([]);
  });
}

test("dialog opened state has no violations", async ({ page }) => {
  await page.goto("/settings");
  await page.getByRole("button", { name: "Delete project" }).click();
  await expect(page.getByRole("dialog")).toBeVisible();

  const results = await new AxeBuilder({ page }).include('dialog').analyze();
  expect(results.violations).toEqual([]);
});

test("keyboard: skip link works and focus is visible", async ({ page }) => {
  await page.goto("/");
  await page.keyboard.press("Tab");
  const skip = page.getByRole("link", { name: "Skip to main content" });
  await expect(skip).toBeFocused();
  await page.keyboard.press("Enter");
  await expect(page.locator("main")).toBeFocused();
});

Notes: scan after interactions that reveal UI (open the menu, dialog, error states), in both light and dark mode, and on mobile viewports. Use .exclude() for third-party widgets you cannot fix, and document each exclusion with an issue link. Print violations helpfully by attaching the JSON to the test report:

test("a11y with attached report", async ({ page }, testInfo) => {
  await page.goto("/");
  const results = await new AxeBuilder({ page }).analyze();
  await testInfo.attach("axe-results", {
    body: JSON.stringify(results.violations, null, 2),
    contentType: "application/json",
  });
  expect(results.violations).toEqual([]);
});

For complete Playwright setup and CI, see Playwright End-to-End Testing: Reliable Suites, Fixtures, Auth and CI at Scale.

Lighthouse and other scanners

Lighthouse runs a subset of axe rules and gives an accessibility score. Use it as a smoke metric, not as proof of compliance: a score of 100 does not mean accessible. Run it in CI with Lighthouse CI (@lhci/cli) and assert a minimum category score and specific audits:

{
  "ci": {
    "collect": { "url": ["http://localhost:3000/", "http://localhost:3000/pricing"], "numberOfRuns": 1 },
    "assert": {
      "assertions": {
        "categories:accessibility": ["error", { "minScore": 0.95 }]
      }
    }
  }
}

Other useful tools: the browser extensions axe DevTools and WAVE, Accessibility Insights for Web (guided assessment), the Chrome DevTools accessibility tree, and Storybook's a11y addon for per-component checks.

CI gates

A sensible pipeline has layered gates:

# .github/workflows/a11y.yml
name: accessibility
on:
  pull_request:
jobs:
  a11y:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npm run lint            # includes jsx-a11y
      - run: npm test                # includes jest-axe component tests
      - run: npx playwright install --with-deps chromium
      - run: npm run build
      - run: npx playwright test e2e/a11y.spec.ts
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report/

Verify the action major versions against their current release pages. For legacy products with many existing violations, use a baseline: record current violations by rule and selector in a file, fail only on new ones, and shrink the baseline over time.

// e2e/a11y-baseline.ts
import baseline from "./a11y-baseline.json";

export function newViolations(results: { violations: Array<{ id: string; nodes: Array<{ target: unknown[] }> }> }, path: string) {
  const known = new Set<string>((baseline as Record<string, string[]>)[path] ?? []);
  return results.violations.flatMap((v) =>
    v.nodes.map((n) => `${v.id}::${String(n.target)}`).filter((key) => !known.has(key)),
  );
}

Component-level and design-time checks

  • Storybook: use the a11y addon (axe under the hood) so each story is scanned, and write an interaction test for keyboard behavior.
  • Design tokens: contrast tests on token pairs, as described in the Tailwind article.
  • Design review: check focus states, target sizes and error states in Figma before building.

Accessibility checklist per component

Use this table in pull requests. If a component does not satisfy a row, either fix it or document why the row is not applicable.

ComponentMust have
ButtonNative button; accessible name; visible focus; target at least 24 by 24 px; type="button" unless submitting; loading state announced; not a styled as button
LinkReal href; descriptive text; distinguishable from surrounding text beyond color; external or download indicated; focus visible
Form fieldVisible label; autocomplete; hint via aria-describedby; error text plus aria-invalid; required indicated in text; group with fieldset and legend
Form (overall)Error summary with focus management; no disabled-submit trap; data preserved on error; no cognitive-test-only authentication
Dialogdialog with showModal() or equivalent inertness; name; focus in and returned; Escape; close button; scroll lock
Menu or disclosureButton with aria-expanded; Escape closes and returns focus; arrow keys only if ARIA menu role used
TabsRoles; roving tabindex; arrow, Home, End; panel labelled by tab
Accordionbutton inside heading; aria-expanded; panel region; or native details
ComboboxRoles and aria-activedescendant; result count announced; Escape; no focus loss on click
ToastLive region present beforehand; does not auto-dismiss too fast (give at least several seconds, or make persistent for errors); not the only way to learn about an error; dismiss control keyboard reachable
TooltipAppears on focus and hover; Escape dismisses; persistent while hovered; no interactive content
Tablecaption; th with scope; no layout tables; sortable column headers are buttons with aria-sort
ImageCorrect alt decision; decorative empty alt; complex image has long description
IconDecorative aria-hidden; functional icon has name on the control
CarouselPause control; keyboard operable; no auto-rotation by default; announce slide changes politely or not at all
Drag and dropKeyboard and single-pointer alternative (2.5.7); announcements for moves
Date pickerAllow typed entry; labelled grid; keyboard arrows; visible format hint
Loading statearia-busy or status message; skeletons hidden from AT; focus not lost
PageUnique title; one h1; landmarks; skip link; language; focus handling on navigation

Where this usually goes wrong

  1. div and span as buttons and links. Fix: native elements.
  2. Removing focus outlines with outline: none and nothing instead. Fix: :focus-visible style.
  3. Placeholder as label. Fix: visible label.
  4. Icon buttons with no name. Fix: aria-label or hidden text, and aria-hidden on the SVG.
  5. Using aria-label on elements where it is not supported (plain div or span with no role). Fix: use visible text or a proper role.
  6. aria-hidden="true" on a parent containing focusable children. Fix: use inert or hidden.
  7. Toasts that inject a new live region. Fix: render the region at load, update its text.
  8. Custom select that cannot be opened with the keyboard. Fix: use native select or a tested library.
  9. Modal that leaves the page scrollable and tabbable. Fix: dialog.showModal().
  10. Positive tabindex. Fix: fix DOM order.
  11. Heading levels chosen by size. Fix: use the right level, style with CSS.
  12. Color-only error indication. Fix: text and an icon.
  13. Auto-playing carousels and videos without controls. Fix: pause control, no autoplay.
  14. Infinite scroll without a way to reach the footer. Fix: provide a "Load more" button or pagination.
  15. Disabling zoom. Fix: remove user-scalable=no.
  16. Inaccessible custom checkboxes where the real input is display: none. Fix: visually hide the native input, keep it focusable, style its sibling.
  17. Mouse-only hover menus. Fix: open on focus and click as well, provide Escape.
  18. Trusting an automated score. Fix: combine with manual testing.
  19. Third-party widgets (chat, cookie banners, maps) assumed accessible. Fix: test them and choose vendors accordingly; the page's conformance includes them.
  20. Reading order broken by CSS. Fix: keep DOM and visual order aligned.

What not to do

  • Don't add ARIA to "make the audit pass". It can make things worse. Fix semantics.
  • Don't build a custom widget library for combobox, menu or date picker unless it is your product. Adopt a headless library that implements APG patterns, then test it.
  • Don't use accessibility overlay widgets that promise one-line compliance. They don't fix underlying markup, can interfere with assistive technology, and have been the subject of regulatory and legal criticism. Fix the source.
  • Don't aim for AAA across the board. WCAG itself says AAA conformance for entire sites is not recommended as a general policy. Adopt AAA criteria where cheap (for example, 7:1 contrast on key text).
  • Don't make every state announce. Over-announcing with live regions is exhausting. Announce outcomes users can't otherwise perceive.
  • Don't separate a "text-only version" of the site. Maintain one accessible site.
  • Don't leave testing to one person. Make it part of the definition of done for every UI story.

A 30-day remediation plan

For an existing product with unknown accessibility status. Adjust to team size; the order matters more than the exact calendar.

Week 1: Measure and stop the bleeding

DayTaskOutput
1Pick the standard: WCAG 2.2 AA. List the top 10 user journeys (sign up, search, checkout, support)Scope document
2Add eslint-plugin-jsx-a11y and fix errors that are autofixable or trivial; enable in CI as a warning, then error for new codeLint gate
3Add axe to Playwright for the top 10 journeys; generate a baseline of violationsBaseline JSON and a report
4Keyboard-only pass of every journey; record blockers (traps, unreachable controls, invisible focus)Issue list tagged P0
5Screen reader pass (VoiceOver or NVDA) of the top 3 journeysIssue list with transcripts

Week 2: Fix the foundations

DayTask
6Global focus style, skip link, lang, page titles, one h1 per page
7Landmarks and heading structure in layouts
8Contrast: fix design tokens in one place; add a token contrast test
9Replace non-native buttons and links; add names to icon buttons
10Review third-party widgets (cookie banner, chat); configure or replace

Week 3: Components and forms

DayTask
11Form fields: labels, autocomplete, hints, error pattern, error summary
12Dialogs: migrate to native dialog or a library; focus return
13Menus, tabs, accordions: verify the keyboard model, or adopt headless primitives
14Combobox and select: replace or wrap with a tested library
15Toasts and live regions; loading states; route change focus and titles

Week 4: Lock it in

DayTask
16Images: alt audit; decorative images empty alt; captions for videos
17Motion: reduced-motion support; stop auto-playing carousels
18Target sizes and dragging alternatives (2.5.7, 2.5.8); focus not obscured (2.4.11)
19Authentication flows (3.3.8) and redundant entry (3.3.7); consistent help (3.2.6)
20Make axe checks blocking in CI for new violations; ratchet the baseline down
21Add a11y section to the pull request template and the Definition of Done
22 to 24Component library documentation: keyboard behavior and ARIA for each component
25 to 26Usability test with at least two people who use assistive technology (paid, with a recruiting partner), if budget allows
27Write an accessibility statement with known limitations and a contact route
28Produce a conformance report (VPAT or ACR) draft from the audit
29Training session: keyboard demo, screen reader demo, the checklist
30Retrospective; set quarterly goals; schedule recurring manual audits

Questions that come up

What WCAG version and level should I target in 2026? WCAG 2.2 Level AA. It is the current Recommendation and includes all 2.1 and 2.0 AA criteria. Many laws still reference 2.1 AA (for example the US ADA Title II rule), so meeting 2.2 AA covers them.

Does the European Accessibility Act apply to my site? It applies to specified consumer products and services (for example e-commerce, consumer banking, e-books, certain transport and communications services) offered in the EU, from 28 June 2025, with exemptions such as microenterprises for services. Whether you are in scope depends on what you sell and to whom. Check with counsel and the national implementing law.

When do I use aria-label versus visible text? Prefer visible text. Use aria-label for icon-only controls, and make sure it contains any visible label text (2.5.3 Label in Name).

What is the difference between aria-hidden, hidden, inert and display: none? display: none and hidden remove content from both rendering and the accessibility tree. aria-hidden="true" removes it from the accessibility tree only (still visible and possibly focusable). inert makes content non-interactive and hidden from AT while still visible. Use inert for background content behind a modal.

What do AI coding assistants get wrong? They tend to generate div buttons, positive or missing tabindex, redundant ARIA, placeholder-only labels, icon buttons without names, and custom modals without focus management. Put the checklist in your agent instructions (for example, require button, label, and native dialog) and run axe and jsx-a11y on generated code.

How often should I do manual screen reader testing? Per feature at release for new interaction patterns, and a regression pass on the top journeys quarterly, or whenever the design system changes core components. If you have mobile web or app users, include mobile: VoiceOver on iOS and TalkBack on Android have different gesture models, so do a smoke test on at least iOS.

Sources and docs