What is tabindex attribute in HTML: Simple Explanation and Examples
tabindex attribute in HTML controls the order in which elements receive keyboard focus when pressing the Tab key. It helps users navigate a webpage using the keyboard by specifying which elements can be focused and in what sequence.How It Works
Think of tabindex as a way to set the order of stops on a bus route, but for keyboard navigation on a webpage. When you press the Tab key, the browser moves the focus from one element to the next. By default, this order follows the page's layout and which elements can be focused naturally, like links and form fields.
Using tabindex, you can change this order or make normally unfocusable elements (like div or span) focusable. Positive numbers set a custom order, zero includes the element in the natural flow, and negative numbers remove the element from keyboard focus.
Example
tabindex values to control the order of keyboard focus.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tabindex Example</title> </head> <body> <button tabindex="2">Second</button> <button tabindex="1">First</button> <button tabindex="3">Third</button> </body> </html>
When to Use
Use tabindex when you want to improve keyboard navigation on your site. For example, if you have custom interactive elements like buttons made from div or span, adding tabindex="0" makes them focusable.
Also, use positive tabindex values sparingly to create a logical focus order different from the page layout, such as in complex forms or dialogs. Avoid overusing positive values because it can confuse users.
Key Points
- tabindex="0" includes element in natural tab order.
- tabindex="-1" makes element focusable only by script, not by Tab key.
- Positive values set explicit tab order but can be confusing if overused.
- Helps improve accessibility and keyboard navigation.