Skip to content
Guest
Learn HTML · Course Syllabus Show lessons
Modern Interactive HTML · 8 min read · Beginner

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

ValueMeaningWhen to Use
tabindex="0"Adds a non-interactive element to the natural DOM tab orderCustom 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 orderNever use: breaks predictable tab navigation!
✓ Keep Focus Visible for Keyboard Users
button:focus-visible {
outline: 3px solid #2563eb;
outline-offset: 2px;
}
✕ Never Hide Focus Outlines
/* 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:

Keyboard Focus & :focus-visible Demo
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. Why should you avoid positive tabindex values like tabindex="2"?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind