Building Accessible Web Components
Build web components that work for everyone: semantic HTML, ARIA roles and states, keyboard navigation, focus management, and screen-reader testing.
On this page
- Introduction
- Start with Semantics: The Free Accessibility
- Keyboard Navigation: Every Interaction Operable Without a Mouse
- Focus Management: Visible Focus and Restoration
- ARIA: Roles, States, and Properties
- Testing: Automated, Manual, and with a Screen Reader
- The Accessibility Tree, Reduced Motion, and High Contrast
- Conclusion
Introduction
An accessible web component is one that every user can perceive, operate, and understand — including users of screen readers, keyboard-only users, users with low vision, and users on touch devices. Accessibility is not a feature you add at the end; it is a set of constraints you design to from the start, and the components built without it are the ones that exclude a quiet minority of users and fail an audit at the worst moment. The good news is that the platform gives you most of what you need for free, through semantic HTML and a small set of ARIA attributes, and the work is in knowing when to use the free stuff and when to extend it. This article covers the four pillars: semantics, keyboard operation, focus management, and ARIA — and the testing that proves they work.
Start with Semantics: The Free Accessibility
The single most effective accessibility practice is to use the HTML element that already conveys the meaning. A <button> is focusable, keyboard-operable (Enter and Space both activate it), and announced as “button” by screen readers, all for free. A <div onclick="..."> is none of those things: it is not focusable by default, it does not respond to the keyboard, and it is announced as nothing. Rebuilding a button from a div is rebuilding, badly, what the platform already gives you.
<!-- Good: semantic, keyboard-operable, announced correctly. -->
<button type="button" onclick="save()">Save</button>
<!-- Bad: a div pretending to be a button. Inaccessible by default. -->
<div class="btn" onclick="save()">Save</div>
The rule extends to every element. Use <nav> for navigation, <main> for the primary content, <article> for a self-contained composition, <ul> and <li> for lists, <label for> for form fields, <fieldset> and <legend> for grouped controls. Each carries semantics that a screen reader announces and that a stylesheet can target, and each is a foundation you build on rather than a void you fill with ARIA. Reach for ARIA only when no semantic element expresses the meaning you need — a tablist, a combobox, a live region — and even then, model it on the closest semantic element.
Keyboard Navigation: Every Interaction Operable Without a Mouse
A component that requires a mouse is a component that excludes keyboard-only users, including many power users and users with motor impairments. Every interaction must be reachable and operable by keyboard alone. The platform handles the basics — Tab moves between focusable elements, Enter and Space activate buttons — but custom components must implement the conventions users expect. A menu should open on the trigger and move focus to the first item; arrow keys should move within the menu; Escape should close it and return focus to the trigger. These are not arbitrary choices; they are the ARIA Authoring Practices patterns that screen-reader users have learned and expect.
function MenuButton() {
const [open, setOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>(null);
return (
<>
<button
ref={buttonRef}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(o => !o)}
onKeyDown={(e) => { if (e.key === "ArrowDown") { setOpen(true); /* move focus to first item */ } }}
>
Menu
</button>
{open && (
<ul role="menu" onKeyDown={(e) => {
if (e.key === "Escape") { setOpen(false); buttonRef.current?.focus(); }
// ArrowUp/ArrowDown move between items, Home/End to first/last
}}>
<li role="menuitem" tabIndex={-1}>Open</li>
<li role="menuitem" tabIndex={-1}>Save</li>
</ul>
)}
</>
);
}
The tabIndex discipline matters: the trigger is in the tab order (tabIndex={0} or, for a button, the default); the menu items are not in the tab order (tabIndex={-1}) but are focusable programmatically, so the arrow keys move focus within the menu without adding every item to the tab sequence. Escape closing the menu and returning focus to the trigger is the pattern that lets a keyboard user dismiss the menu without tabbing through it.
Focus Management: Visible Focus and Restoration
Focus must be visible — every focusable element must show a focus indicator — and it must be managed when the DOM changes. The default browser focus outline is the cheapest accessibility feature you have; removing it (outline: none) without a replacement is the most common accessibility regression. If you must restyle it, replace it with a visible indicator of equal or greater contrast, never remove it.
/* A visible, high-contrast focus indicator. */
:focus-visible {
outline: 2px solid var(--color-focus);
outline-offset: 2px;
}
Manage focus when the component opens and closes. When a dialog opens, move focus into it (to the first focusable element or a heading); when it closes, return focus to the element that opened it, so the user’s focus is not lost to the top of the page. A modal that opens and leaves focus on the trigger behind an overlay is a modal a keyboard user cannot enter.
function Modal({ open, onClose, children, triggerRef }) {
const dialogRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (open) {
const first = dialogRef.current?.querySelector<HTMLElement>("[autofocus], button, a, input");
first?.focus(); // move focus into the modal
} else {
triggerRef.current?.focus(); // restore focus to the trigger
}
}, [open]);
return open ? (
<div ref={dialogRef} role="dialog" aria-modal="true" aria-labelledby="modal-title">
<h2 id="modal-title">Title</h2>
{children}
</div>
) : null;
}
ARIA: Roles, States, and Properties
ARIA is the escape hatch when no semantic element fits. It adds roles, states, and properties to an element that the platform does not provide natively. The first rule of ARIA is to not use ARIA when a native element exists — a <button> is better than role="button" on a div, because the button carries behavior the role does not. The second rule is that ARIA changes the accessibility tree, not the behavior: role="button" on a div tells the screen reader it is a button but does not make it keyboard-operable, so you must add the keyboard handling yourself.
<!-- A toggle expressed with ARIA state. -->
<button id="theme-toggle" aria-pressed="false" onclick="toggleTheme()">
Dark mode
</button>
Use ARIA state for dynamic changes: aria-expanded on a disclosure trigger, aria-pressed on a toggle, aria-checked on a custom checkbox, aria-invalid on a field with an error. Use aria-describedby to associate an error message or hint with a field, and aria-live on a region whose changes should be announced (a search result count, a form error summary). aria-live="polite" announces when the screen reader is idle; aria-live="assertive" interrupts, which is appropriate for errors and rarely for anything else. Overuse of assertive makes the screen reader chatter and the user miss the important announcement in the noise.
Testing: Automated, Manual, and with a Screen Reader
Automated tests catch a subset of issues: missing alt text, insufficient contrast, duplicate ids, violated ARIA rules. Run axe or Lighthouse in CI and treat the failures as build errors, but know that automated tests catch about a third of accessibility issues — the rest require human judgment. Test the keyboard flow manually: unplug the mouse, tab through the component, and confirm every interaction is reachable and operable and the focus indicator is visible at every step. Test with a screen reader — VoiceOver on macOS, NVDA on Windows, TalkBack on Android — and listen to what is actually announced. The component that looks accessible and announces “group, group, group” is not accessible, and only a screen reader tells you.
// A Playwright test that verifies keyboard operability.
test("menu opens with ArrowDown and closes with Escape", async ({ page }) => {
await page.goto("/");
await page.keyboard.press("Tab"); // focus the trigger
await page.keyboard.press("ArrowDown"); // open the menu
await expect(page.getByRole("menuitem", { name: "Open" })).toBeFocused();
await page.keyboard.press("Escape"); // close
await expect(page.getByRole("button", { name: "Menu" })).toBeFocused();
});
The keyboard test is the one that catches the regressions the unit tests cannot see, because it exercises the real interaction model. Write it for every interactive component, and the component stays operable as it evolves.
The Accessibility Tree, Reduced Motion, and High Contrast
The accessibility tree is the browser’s representation of the page as a screen reader perceives it — a tree of nodes with a role, a name, a state, and a value, derived from the DOM but stripped of presentation. A <div> with no role or label is absent from the accessibility tree; a <button> is present with the role “button” and the name from its text content. Understanding the accessibility tree is the key to debugging screen-reader issues, because it is the tree the assistive technology navigates, not the DOM. Inspect it with the browser’s accessibility panel (Chrome DevTools, Firefox Accessibility tab) to see what a screen reader user encounters, which is often different from what a sighted user sees.
<!-- A div with an onClick is in the DOM but not the accessibility tree as a control. -->
<div class="card" onclick="toggle()">Click me</div>
<!-- The button is in both, with role="button" and name="Click me", keyboard-operable by default. -->
<button class="card" onclick="toggle()">Click me</button>
The div-with-onClick is the most common accessibility bug: it is invisible to the accessibility tree as an interactive element, so a screen reader user does not know it is clickable, and it is not keyboard-operable, so a keyboard user cannot activate it. The fix is to use the semantic element (<button>), which puts it in the tree with the right role and the right keyboard behavior for free. If the design truly requires a div, add role="button", tabindex="0", and a keydown handler for Enter and Space — but this is reimplementing the button, and the semantic element is always preferable.
Respect the user’s motion preference. Some users have vestibular disorders for which animation is not a delight but a trigger — vertigo, nausea, seizures. The prefers-reduced-motion media query is the user’s statement that they want less motion, and the application should honor it by reducing or removing animation. A CSS approach that scales animation down rather than removing it entirely is the best balance: a 200ms fade becomes a near-instant 1ms, so the transition still occurs but without the motion.
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
For JavaScript-driven animation (a carousel auto-advance, a confetti burst), check window.matchMedia('(prefers-reduced-motion: reduce)').matches and skip or reduce the animation. Do not override the preference — the user set it for a reason, and an application that ignores it is an application that makes some users ill. The check is a single line; the respect is the discipline.
High contrast mode (prefers-contrast: more) and forced colors mode (Windows High Contrast, which sets forced-colors: active) are the preferences of users who need stronger contrast or a specific color palette. In forced-colors mode, the browser replaces the page’s colors with the user’s system colors, and borders and backgrounds that relied on color for distinction may disappear. Use the Canvas, CanvasText, ButtonFace, and ButtonText system color keywords, and add visible borders (outline or border) that survive the color replacement, so a button that was distinguished by its background color is still distinguishable when the background is gone. Test in Windows High Contrast mode, because it is the environment that breaks the assumptions of color-based design, and it is the environment many users with low vision actually use.
button {
background: var(--color-primary);
color: var(--color-on-primary);
/* A border that survives forced-colors mode, where the background may be replaced. */
border: 1px solid CanvasText;
}
The common thread is that accessibility is not a checklist of attributes but a discipline of considering the user’s environment and preferences. The accessibility tree, the motion preference, the contrast preference, the keyboard, the screen reader — each is a dimension along which the user’s experience differs from the developer’s, and each is honored by a specific technique. The techniques are not hard; the discipline is remembering to apply them, and the test is using the page the way the user does — with the keyboard, with a screen reader, with high contrast, with reduced motion — not just with the mouse and the default theme.
Conclusion
Accessible web components are built on semantic HTML, extended with ARIA only where the platform has no native equivalent, operable entirely by keyboard with the conventions users expect, and managed so focus is visible and restored when the DOM changes. Test automatically in CI for the mechanical issues, manually by keyboard for the interaction model, and with a screen reader for the announced experience. The platform gives you most of this for free when you use the right elements; the work is in not throwing it away and in extending it carefully where it ends. Build to the constraints from the start, and accessibility is a property of the component rather than a retrofit at the audit.
Report a problem with this articleOpens a pre-filled issue on GitHub.