Accessibility rules for coding agents: native elements first
The clickable-div test is the shortest way into web-a11y. Anything with an onclick must be reachable by Tab, activate on Enter and on Space, show a focus ring and announce a role. A <button> does all four. A <div tabindex="0"> with a keydown handler does maybe two, and the Space key is the one that gets forgotten. Resetting a button’s styles takes three declarations: background:none; border:0; font:inherit;.
The modal section lists four obligations: focus moves in, focus is trapped, focus returns to whatever opened it, and the background is inert. Native <dialog> with showModal() covers all four plus Escape. aria-modal="true" alone doesn’t stop Tab.
The skill went into my project-template library in the same commit as Rtl Arabic Web Skill, and the same three repos carry identical copies: my site and two shop sites.
The copy below fixes one real bug. The missing-alt check used a lookahead with grep -E. GNU grep prints warning: ? at start of expression, matches nothing and exits 1, so the check would pass a page full of bare <img> tags. It’s grep -P now. I also cut a “roughly a third” figure for what automated tools catch, which I had no source for, put the skip-link example in English, and trimmed wording throughout.
- name
- web-a11y
- description
- Practical accessibility mechanics for web UI: semantic elements over div soup, keyboard operability, modal dialog focus management, ARIA rules, accessible forms, reduced motion, and contrast. Use when building or reviewing interactive components (modals, accordions, menus, tabs, toasts), when clickable divs or missing focus states appear, or when asked to audit a page for accessibility/WCAG.
Web Accessibility Mechanics
Accessibility is mostly a consequence of using the right element. Most real-world failures trace to a handful of patterns, covered below.
1. The native element first
Before adding a role, ask whether an element already does the job. Native elements bring
keyboard handling, focus, state, and platform accessibility mapping for free, all of which
you would otherwise reimplement and get subtly wrong.
| Instead of | Use |
|---|---|
<div onclick> |
<button type="button"> |
<div onclick> that navigates |
<a href> |
<div> accordion |
<details>/<summary>, or a <button aria-expanded> |
| custom modal | <dialog> with showModal() |
<span> checkbox |
<input type="checkbox"> |
<div> list of items |
<ul>/<li> |
styled <div> page regions |
<header> <nav> <main> <footer> <section> |
The clickable-div test: if an element has an onclick, it must be reachable by Tab,
activate on both Enter and Space, show a visible focus ring, and announce a role. A
<button> does all four. A <div> with tabindex="0" plus a keydown handler does maybe
two, and you will forget Space.
If you must keep the div (layout constraints, existing CSS), the full substitution is:
<div role="button" tabindex="0"
onclick="act()"
onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();act();}">
That is strictly worse than <button>. Reset the button styling instead:
background:none; border:0; font:inherit;.
Nesting rule: an interactive element can never contain another interactive element. A
card that is one big <button> cannot hold a link. Either make the whole card a button, or
make the card a plain container with one clear action inside.
2. Keyboard operability
Everything a mouse can do, a keyboard must do, in a sane order, with a visible indicator.
-
Never remove focus outlines without replacing them. Use
:focus-visibleso the ring appears for keyboard users and not on mouse click::focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }Give the ring enough contrast against both the element and the page background.
-
Never use positive
tabindex.tabindex="1"and up hijack the global tab order. Only0(focusable, in DOM order) and-1(focusable by script only) are legitimate. -
DOM order should match visual order. CSS
order,row-reverseand grid placement can decouple them. If you reorder visually, reorder the DOM. -
Provide a skip link as the first focusable element on any page with navigation:
<a href="#main" class="skip-link">Skip to content</a>Keep it off-screen until
:focus, notdisplay:none(which makes it unfocusable). -
Escape closes things. Any dismissible overlay (modal, menu, popover, drawer) closes on Escape.
3. Modal dialogs: the four obligations
A modal that only toggles a CSS class is not a modal. Four things must happen:
- Focus moves in when it opens: to the dialog, its first control, or its heading.
- Focus is trapped while open: Tab from the last control wraps to the first, Shift+Tab from the first wraps to the last.
- Focus returns to the element that opened it when it closes. Losing focus to
<body>strands keyboard and screen-reader users at the top of the page. - The background is inert, not just visually covered. Content behind a modal must not be reachable by Tab or readable by a screen reader.
Native <dialog> + showModal() provides all four, plus Escape and the backdrop. Prefer it.
For a custom overlay:
<div class="overlay" role="dialog" aria-modal="true" aria-labelledby="dlg-title">
<h2 id="dlg-title">…</h2>
aria-modal="true" tells assistive tech the rest of the page is unavailable, but it does
not stop Tab. You still need the trap, or inert on the page wrapper:
document.getElementById('page').inert = true; // on open
document.getElementById('page').inert = false; // on close
Also restore body scroll on close; body{overflow:hidden} loses the scroll position on iOS
unless you save and restore it.
4. ARIA: the rules that matter
If a native HTML element has the semantics and behavior you need, use it instead of adding ARIA to something else. When you do use ARIA:
- A role is a promise about keyboard behavior.
role="tablist"commits you to arrow-key navigation and roving tabindex. If you're not implementing that, don't claim the role. - State must be kept in sync in JS. A stale
aria-expanded,aria-selected,aria-checkedoraria-pressedis worse than none, because it lies. Update it in the same function that toggles the class. aria-labeloverrides visible text for screen readers. If they disagree, voice-control users saying the visible word can't activate the control. Keep the label a superset of the visible text, or usearia-labelledby.- Icon-only buttons need an accessible name.
titleis not reliable. Usearia-label, and mark the iconaria-hidden="true". - Decorative images take
alt="": empty, not missing. Missingaltmakes screen readers read the filename. - Emoji used as UI need labels. An emoji is read aloud by its full name. Wrap decorative
emoji in
<span aria-hidden="true">.
Live regions announce async changes (toasts, validation, counters, search results):
<div role="status" aria-live="polite" aria-atomic="true"></div>
The region must exist in the DOM before the text is injected; creating and filling it in
the same tick often announces nothing. Use polite for almost everything; assertive is for
genuine errors only.
5. Forms
- Every control has a
<label for>, or is wrapped in one. Placeholder is not a label: it vanishes on input, fails contrast, and isn't reliably announced. - Group related controls in
<fieldset>with a<legend>. - Errors: set
aria-invalid="true", pointaria-describedbyat the message, and put the message next to the field, not only in a summary at the top. Never signal errors with color alone. - Use real
typevalues (email,tel,url,number) andautocompletetokens (name,email,tel). - Never disable the submit button as the only validation feedback; a disabled button gives no explanation and isn't focusable.
6. Motion, contrast, and zoom
Respect reduced motion globally:
@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;
}
}
Scroll-triggered reveals need care: make the default state visible and let JS add the animation, so a JS failure or a reduced-motion setting leaves content readable rather than permanently transparent.
Contrast minimums (WCAG AA): 4.5:1 for body text, 3:1 for large text (≥24px, or ≥19px bold), 3:1 for UI component boundaries and focus indicators. Check both themes independently; muted secondary text on a tinted background is where it usually breaks.
Never convey information by color alone. Pair it with text, an icon, or a pattern.
Zoom to 200% must not clip content or force horizontal scrolling: avoid fixed heights on
text containers and use rem for type.
Target size: at least 24×24px, 44×44px on touch surfaces.
7. Auditing an existing page
Fast static sweep for the usual offenders:
grep -nE 'onclick=' file.html | grep -vE '<(button|a) ' # clickable non-buttons
grep -nE 'outline:\s*(none|0)' file.css # killed focus rings
grep -nE 'tabindex="[1-9]' file.html # positive tabindex
grep -nP '<img(?![^>]*alt=)' file.html # missing alt (needs -P)
grep -nE 'role="dialog"' file.html # then verify focus trap
Then check by hand, in this order:
- Unplug the mouse. Tab through the whole page. Can you reach every control, see where you are at all times, operate everything, and escape every overlay?
- Zoom to 200% and look for clipping.
- Force the OS into reduced motion and reload. Is anything invisible or broken?
- Toggle light/dark and re-check contrast on muted text.
- Run axe DevTools or Lighthouse last. Automated tools miss a large share of issues, including the ones that matter most: focus order, trap behavior, whether a label makes sense.
Fix in order of user impact: keyboard traps and unreachable controls first, missing names second, contrast third, polish after.
---
name: web-a11y
description: Practical accessibility mechanics for web UI: semantic elements over div soup, keyboard operability, modal dialog focus management, ARIA rules, accessible forms, reduced motion, and contrast. Use when building or reviewing interactive components (modals, accordions, menus, tabs, toasts), when clickable divs or missing focus states appear, or when asked to audit a page for accessibility/WCAG.
---
# Web Accessibility Mechanics
Accessibility is mostly a consequence of using the right element. Most real-world failures
trace to a handful of patterns, covered below.
## 1. The native element first
Before adding a `role`, ask whether an element already does the job. Native elements bring
keyboard handling, focus, state, and platform accessibility mapping for free, all of which
you would otherwise reimplement and get subtly wrong.
| Instead of | Use |
|---|---|
| `<div onclick>` | `<button type="button">` |
| `<div onclick>` that navigates | `<a href>` |
| `<div>` accordion | `<details>`/`<summary>`, or a `<button aria-expanded>` |
| custom modal | `<dialog>` with `showModal()` |
| `<span>` checkbox | `<input type="checkbox">` |
| `<div>` list of items | `<ul>`/`<li>` |
| styled `<div>` page regions | `<header> <nav> <main> <footer> <section>` |
**The clickable-div test:** if an element has an `onclick`, it must be reachable by Tab,
activate on both Enter and Space, show a visible focus ring, and announce a role. A
`<button>` does all four. A `<div>` with `tabindex="0"` plus a keydown handler does maybe
two, and you will forget Space.
If you must keep the div (layout constraints, existing CSS), the full substitution is:
```html
<div role="button" tabindex="0"
onclick="act()"
onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();act();}">
```
That is strictly worse than `<button>`. Reset the button styling instead:
`background:none; border:0; font:inherit;`.
**Nesting rule:** an interactive element can never contain another interactive element. A
card that is one big `<button>` cannot hold a link. Either make the whole card a button, or
make the card a plain container with one clear action inside.
## 2. Keyboard operability
Everything a mouse can do, a keyboard must do, in a sane order, with a visible indicator.
- **Never remove focus outlines without replacing them.** Use `:focus-visible` so the ring
appears for keyboard users and not on mouse click:
```css
:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
```
Give the ring enough contrast against *both* the element and the page background.
- **Never use positive `tabindex`.** `tabindex="1"` and up hijack the global tab order. Only
`0` (focusable, in DOM order) and `-1` (focusable by script only) are legitimate.
- **DOM order should match visual order.** CSS `order`, `row-reverse` and grid placement can
decouple them. If you reorder visually, reorder the DOM.
- **Provide a skip link** as the first focusable element on any page with navigation:
```html
<a href="#main" class="skip-link">Skip to content</a>
```
Keep it off-screen until `:focus`, not `display:none` (which makes it unfocusable).
- **Escape closes things.** Any dismissible overlay (modal, menu, popover, drawer) closes on
Escape.
## 3. Modal dialogs: the four obligations
A modal that only toggles a CSS class is not a modal. Four things must happen:
1. **Focus moves in** when it opens: to the dialog, its first control, or its heading.
2. **Focus is trapped** while open: Tab from the last control wraps to the first, Shift+Tab
from the first wraps to the last.
3. **Focus returns** to the element that opened it when it closes. Losing focus to `<body>`
strands keyboard and screen-reader users at the top of the page.
4. **The background is inert**, not just visually covered. Content behind a modal must not
be reachable by Tab or readable by a screen reader.
Native `<dialog>` + `showModal()` provides all four, plus Escape and the backdrop. Prefer it.
For a custom overlay:
```html
<div class="overlay" role="dialog" aria-modal="true" aria-labelledby="dlg-title">
<h2 id="dlg-title">…</h2>
```
`aria-modal="true"` tells assistive tech the rest of the page is unavailable, but it does
*not* stop Tab. You still need the trap, or `inert` on the page wrapper:
```js
document.getElementById('page').inert = true; // on open
document.getElementById('page').inert = false; // on close
```
Also restore body scroll on close; `body{overflow:hidden}` loses the scroll position on iOS
unless you save and restore it.
## 4. ARIA: the rules that matter
If a native HTML element has the semantics and behavior you need, use it instead of adding
ARIA to something else. When you do use ARIA:
- **A role is a promise about keyboard behavior.** `role="tablist"` commits you to arrow-key
navigation and roving tabindex. If you're not implementing that, don't claim the role.
- **State must be kept in sync in JS.** A stale `aria-expanded`, `aria-selected`,
`aria-checked` or `aria-pressed` is worse than none, because it lies. Update it in the
same function that toggles the class.
- **`aria-label` overrides visible text** for screen readers. If they disagree, voice-control
users saying the visible word can't activate the control. Keep the label a superset of the
visible text, or use `aria-labelledby`.
- **Icon-only buttons need an accessible name.** `title` is not reliable. Use `aria-label`,
and mark the icon `aria-hidden="true"`.
- **Decorative images take `alt=""`**: empty, not missing. Missing `alt` makes screen readers
read the filename.
- **Emoji used as UI need labels.** An emoji is read aloud by its full name. Wrap decorative
emoji in `<span aria-hidden="true">`.
**Live regions** announce async changes (toasts, validation, counters, search results):
```html
<div role="status" aria-live="polite" aria-atomic="true"></div>
```
The region must exist in the DOM *before* the text is injected; creating and filling it in
the same tick often announces nothing. Use `polite` for almost everything; `assertive` is for
genuine errors only.
## 5. Forms
- Every control has a `<label for>`, or is wrapped in one. Placeholder is **not** a label: it
vanishes on input, fails contrast, and isn't reliably announced.
- Group related controls in `<fieldset>` with a `<legend>`.
- Errors: set `aria-invalid="true"`, point `aria-describedby` at the message, and put the
message next to the field, not only in a summary at the top. Never signal errors with
color alone.
- Use real `type` values (`email`, `tel`, `url`, `number`) and `autocomplete` tokens (`name`,
`email`, `tel`).
- Never disable the submit button as the only validation feedback; a disabled button gives
no explanation and isn't focusable.
## 6. Motion, contrast, and zoom
**Respect reduced motion** globally:
```css
@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;
}
}
```
Scroll-triggered reveals need care: make the *default* state visible and let JS add the
animation, so a JS failure or a reduced-motion setting leaves content readable rather than
permanently transparent.
**Contrast minimums (WCAG AA):** 4.5:1 for body text, 3:1 for large text (≥24px, or ≥19px
bold), 3:1 for UI component boundaries and focus indicators. Check both themes
independently; muted secondary text on a tinted background is where it usually breaks.
**Never convey information by color alone.** Pair it with text, an icon, or a pattern.
**Zoom to 200%** must not clip content or force horizontal scrolling: avoid fixed heights on
text containers and use `rem` for type.
**Target size:** at least 24×24px, 44×44px on touch surfaces.
## 7. Auditing an existing page
Fast static sweep for the usual offenders:
```bash
grep -nE 'onclick=' file.html | grep -vE '<(button|a) ' # clickable non-buttons
grep -nE 'outline:\s*(none|0)' file.css # killed focus rings
grep -nE 'tabindex="[1-9]' file.html # positive tabindex
grep -nP '<img(?![^>]*alt=)' file.html # missing alt (needs -P)
grep -nE 'role="dialog"' file.html # then verify focus trap
```
Then check by hand, in this order:
1. **Unplug the mouse.** Tab through the whole page. Can you reach every control, see where
you are at all times, operate everything, and escape every overlay?
2. **Zoom to 200%** and look for clipping.
3. **Force the OS into reduced motion** and reload. Is anything invisible or broken?
4. **Toggle light/dark** and re-check contrast on muted text.
5. Run axe DevTools or Lighthouse last. Automated tools miss a large share of issues,
including the ones that matter most: focus order, trap behavior, whether a label makes
sense.
Fix in order of user impact: keyboard traps and unreachable controls first, missing names
second, contrast third, polish after.
see also: Rtl Arabic Web Skill