Web Accessibility - Keyboard Focus and tabindex
Keyboard Focus and tabindex
Many people move around a page with the keyboard only. They press Tab to go to the next link, button, or form field, and Shift + Tab to go back. The element they are on has focus.
Links, buttons, and form fields can get focus by default. Other elements, like <div> and <span>, cannot.
The tabindex Attribute
The tabindex attribute controls whether an element can get focus.
| Value | What it does |
|---|---|
| tabindex="0" | The element can get focus with Tab, in the normal page order |
| tabindex="-1" | The element can get focus only with JavaScript (element.focus()), not with Tab |
| tabindex="1" or higher | Jumps ahead in the Tab order. Avoid this: it makes the order confusing |
Example
<!-- Can be reached with Tab -->
<div tabindex="0">Custom widget</div>
<!-- Can be focused by script, for example after an error -->
<div
tabindex="-1" id="errorTitle">Please fix error</div>
Tip: If you need tabindex="0" to make something clickable, ask yourself if it should be a button instead.
Always Show where Focus is
Users must always see which element has focus. Never remove the focus outline without adding a new one:
Example
/* Do NOT do this */
button:focus {
outline: none;
}
/* Do this
*/
button:focus-visible {
outline: 3px solid #1a73e8;
outline-offset:
2px;
}
The CSS
:focus-visible pseudo-class shows the outline when the user is using the keyboard, but not when they click with a mouse.
Keep a Logical Order
The Tab order follows the order of the HTML. Write your HTML in the same order people read the page, and do not use CSS to move things far from where they are in the code.