Skip to content

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.

18 min read0/4 questions

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.

ElementKeysDetail people get wrong
Link a[href]EnterSpace does not follow a link. It scrolls the page.
ButtonEnter and SpaceEnter fires on key down. Space fires on key up, and can be cancelled by moving focus away first.
CheckboxSpaceEnter does not toggle it.
Radio groupArrowsOne Tab stop for the group. Arrows move and select.
selectArrows, typing lettersAlt+Down (or Space in some browsers) opens the list.
Text inputTyping, EnterEnter in a single-line field submits its form.
details / summaryEnter and SpaceToggles open.
Composite widgetsArrows, Home, EndTabs, menus and listboxes are one Tab stop. ARIA widget patterns has the key maps.
Anything that pops upEscapeCloses 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.

HTML & CSS
<style> .row > * { display: inline-block; margin: 4px 8px 4px 0; padding: 6px 10px; font: inherit; } .fake { background: #e2e8f0; border: 1px solid #64748b; cursor: pointer; } :focus-visible { outline: 2px solid #1d4ed8; outline-offset: 2px; } #log { font: 12px monospace; background: #f8fafc; padding: 6px; min-height: 90px; }</style><p>Click in the preview, Tab to each control, then press Enter and Space.</p><div class="row"> <a href="#nowhere" id="link">A link</a> <button id="btn">A button</button> <div class="fake" id="fake" role="button" tabindex="0">A div role=button</div></div><div id="log" aria-live="off"></div><script> const log = document.getElementById("log"); function say(msg) { log.insertAdjacentHTML("afterbegin", msg + "<br>"); } document.getElementById("link").addEventListener("click", (e) => { e.preventDefault(); say("link: click"); }); document.getElementById("btn").addEventListener("click", () => say("button: click")); const fake = document.getElementById("fake"); function activate() { say("div: activated"); } fake.addEventListener("click", activate); fake.addEventListener("keydown", (e) => { if (e.key === "Enter") activate(); if (e.key === " ") e.preventDefault(); }); fake.addEventListener("keyup", (e) => { if (e.key === " ") activate(); }); document.addEventListener("keydown", (e) => { if (e.key === " " && e.target.id === "link") say("link: Space pressed, no click"); });</script>

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.

Quick check
A link is styled to look like a button, and opens a dialog with JavaScript. A keyboard user presses Space on it. What happens?
Need a nudge? A hint rules out a wrong answer.

tabindex, and the order of things

Only three tabindex values are worth knowing:

  • 0 puts 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.
  • -1 makes an element focusable by script, with el.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 stray tabindex="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.

HTML & CSS
<style> .bar { display: flex; gap: 8px; margin: 10px 0; } .bar.reverse { flex-direction: row-reverse; justify-content: flex-end; } .bar.reorder button:first-child { order: 3; } button:focus-visible { outline: 3px solid #b45309; outline-offset: 2px; }</style><p>Tab through each row. The labels show the DOM order.</p><div class="bar"><button>1</button><button>2</button><button>3</button></div><div class="bar reverse"><button>1</button><button>2</button><button>3</button></div><div class="bar reorder"><button>1</button><button>2</button><button>3</button></div>

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.

Predict the outputHTML

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? -->
Need a nudge? Hints walk you through it.

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 the pairs0/6 matched

Match each moment to where focus should go.

Choose an item, then its match on the other side.

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.

HTML & CSS
<style> .summary { border: 3px solid #b91c1c; padding: 8px 12px; margin-bottom: 12px; } .summary:focus { outline: 3px solid #1d4ed8; outline-offset: 2px; } .summary h2 { font-size: 16px; margin: 0 0 4px; } .err { color: #b91c1c; font-size: 14px; margin: 2px 0 0; } label { display: block; margin-top: 10px; } input { font: inherit; padding: 4px; } input[aria-invalid="true"] { border: 2px solid #b91c1c; } :focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }</style><form id="f" novalidate> <div class="summary" id="summary" tabindex="-1" hidden aria-labelledby="sum-title"> <h2 id="sum-title">There is a problem</h2> <ul id="sum-list"></ul> </div> <label for="name">Full name</label> <input id="name" aria-describedby="name-err"> <p class="err" id="name-err" hidden></p> <label for="email">Email</label> <input id="email" type="email" aria-describedby="email-err"> <p class="err" id="email-err" hidden></p> <p><button>Continue</button></p></form><script> const rules = [ { id: "name", msg: "Enter your full name", bad: (v) => !v.trim() }, { id: "email", msg: "Enter an email address like name@example.com", bad: (v) => !/^\S+@\S+\.\S+$/.test(v) }, ]; document.getElementById("f").addEventListener("submit", (e) => { e.preventDefault(); const list = document.getElementById("sum-list"); list.innerHTML = ""; let errors = 0; for (const r of rules) { const input = document.getElementById(r.id); const err = document.getElementById(r.id + "-err"); const bad = r.bad(input.value); input.setAttribute("aria-invalid", String(bad)); err.hidden = !bad; err.textContent = bad ? "Error: " + r.msg : ""; if (bad) { errors++; list.insertAdjacentHTML("beforeend", '<li><a href="#' + r.id + '">' + r.msg + "</a></li>"); } } const summary = document.getElementById("summary"); summary.hidden = errors === 0; if (errors) summary.focus(); }); document.getElementById("sum-list").addEventListener("click", (e) => { const a = e.target.closest("a"); if (!a) return; e.preventDefault(); document.getElementById(a.getAttribute("href").slice(1)).focus(); });</script>

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 life of a modal, keyboard view
UserTrigger buttonDialogPage behindEntershowModal()made inertEscapefocus restored

The browser remembers the trigger as the element focused before the dialog opened.

1/5

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.

HTML & CSS
<style> dialog, .panel { border: 2px solid #334155; padding: 12px 16px; max-width: 280px; } dialog::backdrop { background: rgb(15 23 42 / 0.5); } .panel { position: fixed; top: 10px; right: 10px; background: white; } button, input { font: inherit; margin: 4px 4px 4px 0; } :focus-visible { outline: 3px solid #b45309; outline-offset: 2px; } #state { font: 12px monospace; color: #475569; }</style><div id="page"> <p>Open each one, press Tab many times, then Escape.</p> <button id="open-native">Native dialog</button> <button id="open-panel">Hand-built panel</button> <p><a href="#x">A link behind</a> <button>A button behind</button></p> <p id="state">focus: none</p></div><dialog id="dlg" aria-labelledby="dlg-title"> <h2 id="dlg-title" style="font-size: 16px; margin-top: 0;">Rename file</h2> <input aria-label="File name" value="report.pdf"> <form method="dialog"><button>Cancel</button><button value="ok">Save</button></form></dialog><div class="panel" id="panel" role="dialog" aria-modal="true" aria-labelledby="panel-title" hidden> <h2 id="panel-title" style="font-size: 16px; margin-top: 0;">Filters</h2> <label><input type="checkbox"> In stock</label><br> <button id="close-panel">Done</button></div><script> const state = document.getElementById("state"); document.addEventListener("focusin", (e) => { const el = e.target; state.textContent = "focus: " + el.tagName.toLowerCase() + " " + (el.textContent.trim() || el.getAttribute("aria-label") || ""); }); const dlg = document.getElementById("dlg"); document.getElementById("open-native").addEventListener("click", () => dlg.showModal()); const panel = document.getElementById("panel"); const page = document.getElementById("page"); let opener = null; function openPanel(e) { opener = document.activeElement === document.body ? e.currentTarget : document.activeElement; panel.hidden = false; page.inert = true; panel.querySelector("input").focus(); } function closePanel() { panel.hidden = true; page.inert = false; if (opener) opener.focus(); } document.getElementById("open-panel").addEventListener("click", openPanel); document.getElementById("close-panel").addEventListener("click", closePanel); panel.addEventListener("keydown", (e) => { if (e.key === "Escape") closePanel(); });</script>

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 it in order5 steps

Put the steps of a hand-built modal panel in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

HTML & CSS
<style> .area { padding: 16px; display: flex; gap: 10px; } .light { background: #ffffff; } .mid { background: #2563eb; } .dark { background: #0f172a; } button { font: inherit; padding: 6px 12px; border: 1px solid #64748b; background: #f1f5f9; } button:focus { outline: none; } .one:focus-visible { outline: 2px solid #2563eb; outline-offset: 2px; } .two:focus-visible { outline: 2px solid #0f172a; outline-offset: 2px; box-shadow: 0 0 0 2px #ffffff; } @media (forced-colors: active) { .two:focus-visible { outline-color: Highlight; } }</style><p>Tab through all three backgrounds. Each "one" button has a single blue ring, each "two" button a two-colour ring.</p><div class="area light"><button class="one">one</button><button class="two">two</button></div><div class="area mid"><button class="one">one</button><button class="two">two</button></div><div class="area dark"><button class="one">one</button><button class="two">two</button></div>

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".

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:

  1. Put the mouse away. Tab from the address bar through the whole page and back with Shift+Tab.
  2. At each stop ask: can I see where I am, is the order sensible, can I operate it with the expected keys?
  3. Open and close everything that pops up. Check where focus lands each time, including after Escape.
  4. 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.

Key terms
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.