Keyboard Navigation
tabindex, focus management, skip links
Skills taught: html.keyboard, html.tabindex, html.focus, html.skip-links
Keyboard users navigate pages with **Tab** (forward), **Shift+Tab** (backward), **Enter** (activate links/buttons), and **Space** (activate buttons/checkboxes).
**Native HTML elements are keyboard-accessible by default.** Always prefer them:
<button>Save</button> <!-- Tab focuses, Enter/Space activates -->
<a href="/about">About</a> <!-- Tab focuses, Enter activates -->
<input type="text"> <!-- Tab focuses, user types -->
<select>...</select> <!-- Tab focuses, arrow keys select -->
<!-- ❌ This receives no keyboard focus -->
<div class="btn" onclick="save()">Save</div>
<!-- ✅ Fix: use a real button -->
<button onclick="save()">Save</button>
**tabindex** controls focusability:
- **tabindex="0"** — adds element to the natural tab order (in DOM order)
- **tabindex="-1"** — focusable by JavaScript only (element.focus()), not by Tab
- **tabindex="1+"** — explicit order (avoid — disrupts natural flow and confuses users)
<!-- Custom component that needs keyboard focus -->
<div role="button" tabindex="0"
onclick="doAction()"
onkeydown="if(event.key==='Enter'||event.key===' ')doAction()">
Custom action
</div>
<!-- Modal that JS focuses programmatically -->
<div role="dialog" tabindex="-1" id="modal">
...
</div>
**Skip links** let keyboard users jump past repeated navigation directly to main content:
<style>
.skip-link {
position: absolute;
top: -40px;
left: 0;
background: #4fd1c5;
color: #0e1116;
padding: 8px 16px;
text-decoration: none;
font-weight: bold;
z-index: 100;
}
.skip-link:focus {
top: 0; /* becomes visible on Tab focus */
}
</style>
<body>
<a class="skip-link" href="#main-content">Skip to main content</a>
<header>...long navigation...</header>
<main id="main-content">
<h1>Keyboard Navigation</h1>
</main>
</body>
Tip:
<style>
/* Remove default outline but add a custom one */
:focus-visible {
outline: 3px solid #4fd1c5;
outline-offset: 2px;
border-radius: 3px;
}
</style>
Frequently Asked Questions
How do I test keyboard accessibility?
Unplug your mouse and navigate your entire site with Tab, Shift+Tab, Enter, Space, and arrow keys. Every feature must be reachable and operable. Also test with NVDA (Windows) or VoiceOver (Mac) to hear the screen reader experience.
Should I ever use a positive tabindex value?
Almost never. Positive tabindex (1, 2, 3…) overrides the natural DOM order and creates a confusing Tab sequence that is hard to maintain. Only the natural order (tabindex=0) is safe.
What is focus trapping in a modal?
When a modal opens, Tab should cycle only within the modal — not back to the page behind it. This requires JavaScript to detect when focus reaches the last focusable element in the modal and redirect it to the first. The inert attribute makes the background non-interactive in modern browsers.