What is tabindex?

tabindex controls whether an element can receive keyboard focus and where it falls in the Tab order. tabindex="0" adds an element to the natural Tab order, tabindex="-1" makes it focusable only from JavaScript (el.focus()), and positive values force a custom order, which you should avoid.

The three values

  • 0: focusable in document order. Use it for custom interactive widgets that are not natively focusable (and give them a role and keyboard handling).
  • -1: removed from the Tab sequence but programmatically focusable. Used for:
    • moving focus to a heading or <main> after client-side navigation,
    • focusing a dialog container or error summary,
    • "roving tabindex" in composite widgets (tabs, toolbars, menus) where only one item is tabbable and arrow keys move between items.
  • Positive (1, 2…): jumps ahead of everything else and creates a confusing order that breaks as the page changes. Treat it as an anti-pattern.

Best practices

  • Prefer native interactive elements (<button>, <a href>, inputs); they are already focusable.
  • Do not add tabindex="0" to static text; screen reader users already have their own reading navigation.
  • Keep the DOM order matching the visual order instead of fixing it with tabindex.
  • Make focus visible with :focus-visible styles.
  • Use the inert attribute to make whole regions (like content behind a modal) unfocusable.

Interview tip

Explaining the roving tabindex pattern is a strong signal of practical accessibility experience.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 [role="toolbar"] button[tabindex="0"] { outline: 2px dashed #2b4bff; }
4 :focus-visible { outline: 3px solid #e11d48 !important; outline-offset: 2px; }
5</style>
6<a href="#">Before</a>
7<div role="toolbar" aria-label="Text formatting">
8 <button tabindex="0">Bold</button>
9 <button tabindex="-1">Italic</button>
10 <button tabindex="-1">Underline</button>
11</div>
12<a href="#">After</a>
13<h2 id="results" tabindex="-1">Results</h2>
14<button id="search">Search (moves focus to Results)</button>
15<script>
16 // Roving tabindex: Tab enters the toolbar once; arrows move inside it
17 const items = [...document.querySelectorAll('[role="toolbar"] button')];
18 items.forEach((btn, i) =>
19 btn.addEventListener("keydown", (e) => {
20 const dir = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
21 if (!dir) return;
22 const next = items[(i + dir + items.length) % items.length];
23 items.forEach((b) => (b.tabIndex = -1));
24 next.tabIndex = 0;
25 next.focus();
26 })
27 );
28 // tabindex="-1": focusable from script, not with Tab
29 document.getElementById("search").onclick = () => document.getElementById("results").focus();
30</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app