Lesson 30 of 52Accessibility in depth
Keyboard Support and Focus Management
Learn the keyboard contract of each element, manage focus through modals, errors and route changes, and design focus styles that pass WCAG everywhere.
A customer writes in: "I use the keyboard because of an injury. On your settings page, after I save, I am sent back to the top of the page and have to tab forty times to get back." Another ticket says the "Delete account" modal lets focus wander into the page behind it. A third says the focus ring disappears on the dark footer. None of these show up in a screenshot or a click-through demo, and all three fail WCAG. Keyboard support is not only "can I reach it with Tab". It is where focus goes at every moment, what each key does, and whether people can see it. This lesson goes past the basics into the details that separate an app that technically works from one keyboard users trust.
The keyboard contract
Accessibility basics covered Tab, Shift+Tab, Enter and Space. The details matter more than people think, because users expect the same keys to do the same things on every site.
| Element | Keys | Detail people get wrong |
|---|---|---|
Link a[href] | Enter | Space does not follow a link. It scrolls the page. |
| Button | Enter and Space | Enter fires on key down. Space fires on key up, and can be cancelled by moving focus away first. |
| Checkbox | Space | Enter does not toggle it. |
| Radio group | Arrows | One Tab stop for the group. Arrows move and select. |
select | Arrows, typing letters | Alt+Down (or Space in some browsers) opens the list. |
| Text input | Typing, Enter | Enter in a single-line field submits its form. |
details / summary | Enter and Space | Toggles open. |
| Composite widgets | Arrows, Home, End | Tabs, menus and listboxes are one Tab stop. ARIA widget patterns has the key maps. |
| Anything that pops up | Escape | Closes it and returns focus to the trigger. |
This is why a real button beats div role="button". To match the button you must handle Enter on keydown, Space on keyup, stop Space from scrolling the page on keydown, add tabindex="0", and still handle disabled state. Try the keys in the preview and watch which events fire.
Preview
Fourteen lines to get one fake button almost right, and it still has no disabled state and no form submission. The real button got all of it for free.
tabindex, and the order of things
Only three tabindex values are worth knowing:
0puts an element in the natural tab order, at its place in the DOM. Use it only on custom widgets that have a role and keyboard handling.-1makes an element focusable by script, withel.focus(), but not with Tab. This is how you send focus to a heading after a route change, to an error summary, or to the panel of a roving tabindex widget.- Positive values (
1,5,99) jump the queue. Every positive element is visited first in ascending order, then everything else. One straytabindex="1"in a header makes the whole page's order surprising. Never use them.
The order Tab follows is the DOM order, not the visual order. CSS can make the two disagree: flex-direction: row-reverse, the order property, grid-template-areas or grid placement, and absolute positioning all move boxes without moving the source. WCAG 2.4.3 Focus Order (A) requires an order that preserves meaning, and focus jumping backwards across the screen fails it.
Preview
The first row is fine. In the second, focus moves right to left against the reading direction. In the third, focus starts at the far right and then jumps back. The fix is to change the HTML order and keep CSS for layout, or use these properties only where the order carries no meaning. A newer CSS property, reading-flow, lets a flex or grid container tell the browser to follow the visual order for focus and reading. Chromium has shipped it; check current support in other browsers before you rely on it.
What does this print?
<button>A</button> <button tabindex="2">B</button> <button tabindex="0">C</button> <button tabindex="1">D</button> <button tabindex="-1">E</button> <!-- Tab order starting from the address bar? -->
Where focus goes, and when
Accessible React components walked through focus after deleting an item and on client route changes. The underlying rule is the same in any stack: whenever the focused element disappears or the context changes, you decide where focus goes. If you do not, the browser usually drops it on body, and the next Tab starts from the top of the page. That is the "forty tabs" ticket.
Match each moment to where focus should go.
Error summaries are worth a closer look, because they are the pattern government services use and the one that tests best with real users. On submit, render a box at the top of the form with a heading and one link per error, then focus the box. Each link jumps to its field.
Preview
Press Continue with the fields empty. Focus lands on the summary, and a screen reader reads "There is a problem" followed by the list. The summary has tabindex="-1" so it can be focused by script but is not an extra Tab stop. Each field gets aria-invalid and an aria-describedby message starting with "Error:", so the problem is not carried by the red border alone.
Modals: inert does the trapping
A modal must keep focus inside it while it is open. The old way was a JavaScript "focus trap" that intercepted Tab on the last element and wrapped to the first. It is fiddly and still lets screen reader users wander out with their own navigation keys. The modern way is to make everything outside the modal inert.
The inert attribute (Baseline since 2023) makes a subtree unfocusable, unclickable and hidden from assistive tech in one go. And dialog.showModal() makes the rest of the page inert for you, moves focus in, closes on Escape, and returns focus to the trigger when it closes.
The browser remembers the trigger as the element focused before the dialog opened.
When you cannot use dialog, for example a full-screen mobile menu or a side panel that is part of the layout, apply the same idea by hand: put inert on the main content, move focus in, handle Escape, and restore focus when closing. Compare the two in the preview.
Preview
Safari does not focus a button when it is clicked, so document.activeElement can be body at that moment. The code falls back to the clicked trigger for that case. In both, Tab never reaches the link or button behind. Notice that the panel is a sibling of the inert content, not inside it, because inert applies to the whole subtree. With the native dialog, Tab from the last button may move into the browser's own toolbar before coming back. That is expected and is not a keyboard trap: the user can always get back.
Put the steps of a hand-built modal panel in order.
- Tap the steps below in the right order.
Focus styles that pass everywhere
WCAG 2.4.7 (AA) requires a visible indicator. 1.4.11 requires 3 to 1 contrast for it against what is next to it. 2.4.13 (AAA) adds a size: at least a 2 CSS px perimeter, with 3 to 1 contrast between focused and unfocused states. A design that meets the AAA rule is a sensible default, because it fixes the common complaint that focus is "there but hard to see".
The hard case is a single brand colour ring. Blue on white passes, but the same blue on a navy footer disappears. A two-colour ring works on any background: a light inner ring and a dark outer ring, so one of them always contrasts.
Preview
The box-shadow fills the 2 px gap created by outline-offset with white, and the dark outline sits outside it. The single blue ring vanishes on the blue strip. On the dark strip, the two-colour ring's white inner ring carries it.
Two details keep this working in forced colors mode, which Windows High Contrast themes use. In that mode the browser replaces your colours with the user's system colours and removes box-shadow entirely. A focus style built only from box-shadow, with outline: none, therefore shows nothing at all. Keep a real outline in every focus style, even outline: 2px solid transparent when the visible ring is a shadow: in forced colors the transparent outline is repainted in a system colour and becomes visible. You can test this in Chrome DevTools under Rendering, "Emulate CSS media feature forced-colors".
Skip links and sticky headers
A skip link should be the first focusable element and visible when focused. Hiding it with display: none removes it from the tab order, so use a visually hidden style that is undone on focus:
.skip {
position: absolute;
left: 8px;
top: -100px;
}
.skip:focus {
top: 8px;
padding: 8px 12px;
background: #0f172a;
color: #ffffff;
z-index: 100;
}<a class="skip" href="#main">Skip to main content</a>
<header>...</header>
<main id="main" tabindex="-1">...</main>The tabindex="-1" on main makes older browsers move focus, not only the scroll position, so the next Tab continues from the main content. With a sticky header, add scroll-padding-top to html (WCAG 2.2 explained showed the 2.4.11 demo), or scroll-margin-top on the targets, so the skip target and every focused element stop below the header.
Testing keyboard support
Keyboard traps (2.1.2, level A) are the one keyboard failure that blocks a user completely: focus enters a widget and Tab, Shift+Tab and Escape cannot get it out. Embedded maps, rich text editors and some video players are common culprits. Rich text editors legitimately capture Tab for indentation; WCAG accepts that only if you tell the user how to leave, for example "press Escape, then Tab".
A practical routine for every page or feature:
- Put the mouse away. Tab from the address bar through the whole page and back with Shift+Tab.
- At each stop ask: can I see where I am, is the order sensible, can I operate it with the expected keys?
- Open and close everything that pops up. Check where focus lands each time, including after Escape.
- Trigger every async change: save, delete, submit with errors, paginate. Did focus survive?
When you lose track of focus, let the browser tell you. In Chrome DevTools, click the eye icon in the Console to create a Live Expression and type document.activeElement. It updates as you tab. Or paste a logger:
document.addEventListener("focusin", (e) => {
console.log("focus:", e.target);
});
document.addEventListener("focusout", (e) => {
if (!e.relatedTarget) console.warn("focus left with no target, check for focus loss", e.target);
});The warning fires when focus leaves an element and nothing receives it, which is the signature of focus falling to body after a removed node. It also fires when focus leaves the page for the browser's toolbar, so read it with that in mind.
- tab order
- The sequence Tab follows. It is the DOM order, with positive tabindex values visited first.
- tabindex='-1'
- Makes an element focusable by script but skipped by Tab. Used for headings, summaries and roving items.
- focus management
- Deciding where focus goes when content opens, closes, changes or disappears.
- keyboard trap
- A place focus can enter but not leave with standard keys. Fails WCAG 2.1.2 at level A.
- error summary
- A focused box at the top of a form that lists each error as a link to its field.
- forced colors
- A mode, used by Windows contrast themes, where the browser replaces page colours with system colours and removes box-shadow.
- skip link
- The first link on a page, visible on focus, that jumps past repeated navigation to the main content.