Focus & Keyboard Accessibility
Design effortless keyboard navigation by respecting natural DOM tab order, using tabindex correctly, and styling :focus-visible.
What you'll learn
- Understand which HTML elements are focusable by default
- Know the difference between tabindex="0", tabindex="-1", and why positive tabindex is an anti-pattern
- Style crisp keyboard focus indicators with :focus-visible
Millions of users navigate the web with a keyboard (Tab, Shift + Tab, Enter, Space), whether due to motor disabilities, screen readers, or power-user speed.
Naturally Focusable Elements
Links (<a href>), <button>, <input>, <select>, <textarea>, and <summary> are automatically in the keyboard tab order. Generic <div> and <span> elements are not.
Understanding tabindex
| Value | Meaning | When to Use |
|---|---|---|
tabindex="0" | Adds a non-interactive element to the natural DOM tab order | Custom scrollable regions or custom ARIA widgets |
tabindex="-1" | Not reachable via Tab, but can receive focus via el.focus() | Jumping focus to a heading or error summary after form submit |
tabindex="1" (positive) | Forces an element ahead of natural order | Never use: breaks predictable tab navigation! |
button:focus-visible {
outline: 3px solid #2563eb;
outline-offset: 2px;
} /* Traps keyboard users in the dark! */
button:focus {
outline: none;
} :focus-visible shows the ring for keyboard navigation while staying clean on mouse clicks.
Fill-in-the-Blank Exercise
Programmatic Focus Target
Make the alert heading focusable via JavaScript without adding it to the normal Tab order, and style keyboard focus cleanly.
<h2 id="errorBanner" tabindex="">Please fix 2 errors</h2>
<style>
button: {
outline: 2px solid #2563eb;
}
</style>Try It Yourself
Click inside the preview and press Tab to move across the buttons, then click Jump to Main Heading to see tabindex="-1" programmatic focus:
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. Why should you avoid positive tabindex values like tabindex="2"?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.