---
name: accessibility-patterns
description: Web accessibility (a11y) patterns for WCAG compliance, ARIA usage, semantic HTML, keyboard navigation, and focus management. Use when building accessible UI, reviewing components for a11y, adding ARIA attributes, handling keyboard interactions, or when the user asks about accessibility, WCAG, screen readers, or focus management.
title: accessibility-patterns
canonical_url: https://skilld.dev/gh/grahamcrackers/skills/accessibility-patterns
last_updated: 2026-10-07T02:20:44.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install grahamcrackers/skills/accessibility-patterns`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/accessibility-patterns`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/grahamcrackers/skills/accessibility-patterns) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/accessibility-patterns`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/accessibility-patterns --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/accessibility-patterns --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Accessibility Patterns

## Semantic HTML First

Use the correct HTML element before reaching for ARIA. Native elements provide keyboard behavior, focus management, and screen reader semantics for free:

| Need       | Use                                   | Not                     |
| ---------- | ------------------------------------- | ----------------------- |
| Button     | `<button>`                            | `<div onClick>`         |
| Link       | `<a href>`                            | `<span onClick>`        |
| Navigation | `<nav>`                               | `<div class="nav">`     |
| List       | `<ul>` / `<ol>`                       | `<div>` with divs       |
| Heading    | `<h1>`–`<h6>`                         | `<div class="title">`   |
| Form field | `<input>` / `<select>` / `<textarea>` | `<div contenteditable>` |
| Dialog     | `<dialog>`                            | `<div class="modal">`   |

The first rule of ARIA: don't use ARIA if a native HTML element does the job.

## ARIA Essentials

When native elements aren't sufficient:

### Roles

Add semantic meaning to generic elements:

```html
<div role="tablist">
    <button role="tab" aria-selected="true">Tab 1</button>
    <button role="tab" aria-selected="false">Tab 2</button>
</div>
<div role="tabpanel">Content</div>
```

### States and Properties

Communicate dynamic state to assistive technology:

```html
<button aria-expanded="false" aria-controls="menu-content">Menu</button>
<div id="menu-content" hidden>...</div>

<input aria-invalid="true" aria-describedby="error-msg" />
<span id="error-msg">Email is required</span>
```

### Live Regions

Announce dynamic content changes:

```html
<div aria-live="polite" aria-atomic="true">3 results found</div>

<div role="alert">Your session is about to expire.</div>
```

- `aria-live="polite"` — announces after current speech finishes.
- `aria-live="assertive"` or `role="alert"` — interrupts immediately (use sparingly).

### Labels

Every interactive element needs an accessible name:

```html
<!-- Visible label (preferred) -->
<label for="email">Email</label>
<input id="email" type="email" />

<!-- aria-label for icon-only buttons -->
<button aria-label="Close dialog"><CloseIcon /></button>

<!-- aria-labelledby for complex labels -->
<h2 id="section-title">Billing</h2>
<form aria-labelledby="section-title">...</form>
```

## Keyboard Navigation

### Focus Order

- Ensure logical tab order follows visual layout. Don't use `tabindex` > 0.
- Use `tabindex="0"` to make non-interactive elements focusable when necessary.
- Use `tabindex="-1"` to make elements programmatically focusable but not in the tab order.

### Key Handlers

Implement expected keyboard patterns for custom widgets:

| Widget   | Keys                                                     |
| -------- | -------------------------------------------------------- |
| Button   | Enter, Space to activate                                 |
| Menu     | Arrow keys to navigate, Enter to select, Escape to close |
| Tabs     | Arrow keys to switch, Enter/Space to activate            |
| Dialog   | Escape to close, trap focus inside                       |
| Combobox | Arrow keys to navigate, Enter to select, Escape to close |

```tsx
function handleKeyDown(e: React.KeyboardEvent) {
    switch (e.key) {
        case "ArrowDown":
            e.preventDefault();
            focusNextItem();
            break;
        case "ArrowUp":
            e.preventDefault();
            focusPreviousItem();
            break;
        case "Escape":
            closeMenu();
            break;
    }
}
```

### Focus Trapping

Modal dialogs must trap focus — Tab and Shift+Tab cycle only through elements inside the dialog:

```tsx
function trapFocus(dialogRef: RefObject<HTMLDialogElement>) {
    const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
    );
    const first = focusable?.[0];
    const last = focusable?.[focusable.length - 1];

    function handleTab(e: KeyboardEvent) {
        if (e.key !== "Tab") return;
        if (e.shiftKey && document.activeElement === first) {
            e.preventDefault();
            last?.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
            e.preventDefault();
            first?.focus();
        }
    }

    dialogRef.current?.addEventListener("keydown", handleTab);
}
```

### Focus Restoration

When a dialog/popover closes, return focus to the element that triggered it:

```tsx
const triggerRef = useRef<HTMLButtonElement>(null);

function openDialog() {
    triggerRef.current = document.activeElement as HTMLButtonElement;
    setOpen(true);
}

function closeDialog() {
    setOpen(false);
    triggerRef.current?.focus();
}
```

## Color and Contrast

- Minimum contrast ratio: **4.5:1** for normal text, **3:1** for large text (WCAG AA).
- Never rely on color alone to convey meaning — add icons, text, or patterns.
- Test with forced-colors mode (Windows High Contrast).

## Motion

Respect the user's motion preference:

```css
@media (prefers-reduced-motion: reduce) {
    *,
    *::before,
    *::after {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
    }
}
```

```tsx
const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
```

## Forms

- Associate every input with a `<label>`.
- Group related fields with `<fieldset>` and `<legend>`.
- Display error messages inline, linked with `aria-describedby`.
- Use `aria-required="true"` or the `required` attribute.
- Mark invalid fields with `aria-invalid="true"`.

## Images

```html
<!-- Informative image -->
<img src="chart.png" alt="Sales increased 25% in Q4 2025" />

<!-- Decorative image -->
<img src="divider.svg" alt="" role="presentation" />

<!-- Complex image -->
<figure>
    <img src="diagram.png" alt="System architecture overview" />
    <figcaption>Request flow from client through API gateway to microservices</figcaption>
</figure>
```

## Testing

- **Keyboard-only**: Tab through the entire page without a mouse.
- **Screen reader**: Test with VoiceOver (macOS), NVDA (Windows), or TalkBack (Android).
- **Automated**: Use `axe-core`, `eslint-plugin-jsx-a11y`, or Lighthouse accessibility audit.
- **Manual**: Zoom to 200%, use forced colors, test with `prefers-reduced-motion`.
- **Testing Library**: Use `getByRole`, `getByLabelText` — if you can't query by role, the component may have an a11y issue.
