Skip to content
jshacks.dev
Browser

How to Build an Accessible Tabs Component

Build an accessible tabs component with tablist, tab and tabpanel roles, arrow key navigation, roving tabindex, manual activation and URL hash support.

9 min read
Summarize in AI
Flat illustration of a template rendering into a page, with the Google Chrome, React, Svelte and CSS logos.

Tabs are a standard way to fit related views into one place: a product's description, specifications and reviews, the sections of a settings page, code samples in different languages. They are also one of the components most often built wrongly. A row of styled div elements that react to clicks works for a mouse user and is invisible to everyone else: a keyboard user cannot reach the second tab, a screen reader announces nothing about tabs or panels and the selected state is only a color. The WAI-ARIA Authoring Practices describe exactly how a tab interface should behave, with specific roles, states and keyboard interactions that assistive technology understands. This guide shows how to build an accessible tabs component: the markup with tablist, tab and tabpanel roles, the ARIA attributes that connect them, the script for selection with the roving tabindex pattern, arrow keys, Home and End, automatic and manual activation, handling the URL hash, orientation and vertical tabs, responsive behavior, when not to use tabs and how to test with a keyboard and a screen reader. The pattern is documented in the WAI-ARIA Authoring Practices Guide and on MDN.

The markup

The structure has three parts. A container with role="tablist" holds the tabs. Each tab is a <button> with role="tab", an aria-selected state and an aria-controls that names its panel. Each panel is an element with role="tabpanel", labeled by its tab through aria-labelledby, and hidden unless selected.

tabs.htmlHTML
<div class="tabs" id="product-tabs">
  <div role="tablist" aria-label="Product information">
    <button role="tab" id="tab-description" aria-selected="true" aria-controls="panel-description">
      Description
    </button>
    <button role="tab" id="tab-specs" aria-selected="false" aria-controls="panel-specs" tabindex="-1">
      Specifications
    </button>
    <button role="tab" id="tab-reviews" aria-selected="false" aria-controls="panel-reviews" tabindex="-1">
      Reviews
    </button>
  </div>

  <div role="tabpanel" id="panel-description" aria-labelledby="tab-description" tabindex="0">
    <p>A durable backpack for daily commuting.</p>
  </div>
  <div role="tabpanel" id="panel-specs" aria-labelledby="tab-specs" tabindex="0" hidden>
    <p>Capacity 24 liters. Weight 900 grams.</p>
  </div>
  <div role="tabpanel" id="panel-reviews" aria-labelledby="tab-reviews" tabindex="0" hidden>
    <p>Rated 4.6 out of 5 by 128 customers.</p>
  </div>
</div>
Text
(three tabs and three panels, with only the first selected and visible)

Using <button> elements gives the tabs keyboard focus and Enter and Space activation for free. The aria-label on the tablist names the group for screen readers. Only the selected tab is in the page's tab order; the others have tabindex="-1", which makes them focusable by script and the arrow keys but not by Tab. This is the roving tabindex pattern, which keeps the widget a single stop in the Tab sequence. The panels have tabindex="0" so that a keyboard user can move from the tab into the panel content when it has no focusable child, which lets them scroll it. Hidden panels use the hidden attribute, which removes them from the accessibility tree and from rendering.

The behavior

The script has three jobs: select a tab, update all the states and handle keys. Start with selection.

select.jsJavaScript
function createTabs(root) {
  const tablist = root.querySelector('[role="tablist"]');
  const tabs = [...tablist.querySelectorAll('[role="tab"]')];
  const panels = tabs.map((tab) => document.getElementById(tab.getAttribute("aria-controls")));

  function select(index, { focus = false } = {}) {
    tabs.forEach((tab, i) => {
      const selected = i === index;
      tab.setAttribute("aria-selected", String(selected));
      tab.tabIndex = selected ? 0 : -1;
      panels[i].hidden = !selected;
    });
    if (focus) tabs[index].focus();
  }

  tabs.forEach((tab, index) => {
    tab.addEventListener("click", () => select(index));
  });

  return { tabs, panels, select };
}

const tabs = createTabs(document.querySelector("#product-tabs"));
tabs.select(1);
console.log(tabs.tabs[1].getAttribute("aria-selected"), tabs.panels[1].hidden);
Text
true false

select() sets aria-selected on exactly one tab, moves the roving tabindex to it and shows its panel while hiding the others. Because it works from the tab list in the DOM, adding a tab means adding markup, with no code changes.

Keyboard interaction

The specification defines the keys. Arrow Left and Arrow Right move to the previous and next tab for a horizontal tablist, wrapping from the last to the first and the other way. Home moves to the first tab and End to the last. Tab leaves the tablist and moves into the panel, or to the next focusable element. Delete may be used when tabs can be closed.

keys.jsJavaScript
function createTabs(root) {
  const tablist = root.querySelector('[role="tablist"]');
  const tabs = [...tablist.querySelectorAll('[role="tab"]')];
  const panels = tabs.map((tab) => document.getElementById(tab.getAttribute("aria-controls")));
  const vertical = tablist.getAttribute("aria-orientation") === "vertical";
  const prevKey = vertical ? "ArrowUp" : "ArrowLeft";
  const nextKey = vertical ? "ArrowDown" : "ArrowRight";

  function select(index, { focus = false } = {}) {
    tabs.forEach((tab, i) => {
      const selected = i === index;
      tab.setAttribute("aria-selected", String(selected));
      tab.tabIndex = selected ? 0 : -1;
      panels[i].hidden = !selected;
    });
    if (focus) tabs[index].focus();
  }

  tablist.addEventListener("keydown", (event) => {
    const current = tabs.indexOf(document.activeElement);
    if (current === -1) return;

    let next = null;
    if (event.key === nextKey) next = (current + 1) % tabs.length;
    else if (event.key === prevKey) next = (current - 1 + tabs.length) % tabs.length;
    else if (event.key === "Home") next = 0;
    else if (event.key === "End") next = tabs.length - 1;

    if (next !== null) {
      event.preventDefault();
      select(next, { focus: true });
    }
  });

  tabs.forEach((tab, index) => tab.addEventListener("click", () => select(index)));
  return { select };
}
Text
(arrow keys, Home and End move focus and selection between tabs; Tab moves out of the list)

For a vertical tablist, set aria-orientation="vertical", and use Up and Down arrow keys instead of Left and Right, which the code does by reading the attribute. Calling preventDefault() for these keys stops the page from scrolling.

Automatic or manual activation

The pattern allows two designs. With automatic activation, moving focus with the arrow keys also selects the tab and shows its panel at once, as the code above does. It is the simplest for users when the panels show immediately, and recommended when content is available without delay. With manual activation, arrow keys move focus only, and the user presses Enter or Space to select. That is better when showing a panel is slow, for instance when it loads data from a server, because moving through the tabs does not trigger a request for each.

manual.jsJavaScript
tablist.addEventListener("keydown", (event) => {
  const current = tabs.indexOf(document.activeElement);
  if (current === -1) return;

  if (event.key === "ArrowRight" || event.key === "ArrowLeft") {
    event.preventDefault();
    const next = (current + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;
    tabs[next].focus();
  }
  if (event.key === "Enter" || event.key === " ") {
    event.preventDefault();
    select(current);
  }
});
Text
(arrow keys only move focus, and Enter or Space selects the focused tab)

With manual activation, the roving tabindex still moves with the focus, so that the focused tab is the one in the tab order. Pick one mode and use it consistently on the site.

Style the states

Style from the ARIA attributes, so that the visual state and the accessible state never disagree. A focus indicator must be visible, and the selected tab needs a cue that does not rely on color alone.

tabs.cssCSS
[role="tablist"] {
  display: flex;
  gap: 0.25rem;
  border-bottom: 1px solid #d1d5db;
}

[role="tab"] {
  padding: 0.6rem 1rem;
  border: 0;
  border-bottom: 3px solid transparent;
  background: none;
  font: inherit;
  cursor: pointer;
}

[role="tab"][aria-selected="true"] {
  border-bottom-color: #0b5fff;
  font-weight: 600;
}

[role="tab"]:focus-visible {
  outline: 3px solid #0b5fff;
  outline-offset: -3px;
}

[role="tabpanel"]:focus-visible {
  outline: 3px solid #0b5fff;
}

@media (forced-colors: active) {
  [role="tab"][aria-selected="true"] {
    border-bottom-color: Highlight;
  }
}
Text
(the selected tab has a thick underline and bold text, and keyboard focus shows a clear outline)

The bold weight in addition to the underline means the selected state is not conveyed by color alone. The forced-colors rule keeps the indicator visible in Windows high contrast mode, where author colors are replaced.

Tabs that people may want to share or return to should be reflected in the URL. Use the hash: select the tab named in location.hash on load, and update the hash when the selection changes, with history.replaceState to avoid filling the history with entries.

hash.jsJavaScript
function selectFromHash(tabs, select) {
  const id = location.hash.slice(1);
  const index = tabs.findIndex((tab) => tab.getAttribute("aria-controls") === id);
  if (index !== -1) select(index);
}

const instance = createTabs(root);
const tabButtons = [...root.querySelectorAll('[role="tab"]')];

selectFromHash(tabButtons, instance.select);
window.addEventListener("hashchange", () => selectFromHash(tabButtons, instance.select));

tabButtons.forEach((tab) => {
  tab.addEventListener("click", () => {
    history.replaceState(null, "", `#${tab.getAttribute("aria-controls")}`);
  });
});
Text
(opening page.html#panel-specs shows the Specifications tab)

A link elsewhere on the page that points to #panel-reviews then opens the right tab through the hashchange listener.

Do not hide content from search and printing

The hidden panels are in the HTML, so search engines and assistive technology can read them when they are shown, and Ctrl+F in some browsers can find text in hidden panels and reveal them if you use hidden="until-found", supported in current Chromium-based browsers, along with the beforematch event to select the right tab. For print, a stylesheet can show all panels so the printout is complete.

print.cssCSS
@media print {
  [role="tablist"] {
    display: none;
  }

  [role="tabpanel"][hidden] {
    display: block !important;
  }
}
Text
(printing the page includes the content of every tab)

Responsive design

On narrow screens, a row of many tabs can overflow. Options are to let the tablist scroll horizontally with overflow-x: auto and make sure the selected tab scrolls into view, to wrap the tabs or to turn the component into an accordion at small widths. If it becomes an accordion, the semantics change: use buttons with aria-expanded and regions, not tab roles, and switch the markup, not only the style. Keep tab labels short, and avoid more than five or six tabs in one list.

scroll.jsJavaScript
function revealTab(tab) {
  tab.scrollIntoView({ block: "nearest", inline: "center", behavior: "smooth" });
}
Text
(the selected tab is scrolled into view in an overflowing tab list)

When tabs are the wrong choice

Tabs suit parallel views of one thing where the user needs one at a time. They are not navigation between pages, for which plain links and aria-current="page" are correct, and not a place to hide content that every visitor needs to read, since many will never click the second tab. They are not appropriate when the sections should be compared side by side, or for long sequential content, which is better as a page with headings. If the component behaves as a disclosure for each section, use <details> or an accordion pattern.

Test it

Use the keyboard alone: Tab into the tablist, check that the selected tab has focus, press the arrow keys and watch focus and selection move, press Home and End, then press Tab to reach the panel. Test with VoiceOver, NVDA or JAWS, which should announce the tab name, "tab", its position, such as "2 of 3" and the selected state, and then the panel. Check contrast and focus indicators, zoom to 200 percent and Windows high contrast mode. In automated tests, assert the attributes after each key press.

test.jsJavaScript
const tab = document.querySelector("#tab-specs");
tab.focus();
tab.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }));

console.log(document.activeElement.id, document.activeElement.getAttribute("aria-selected"));
Text
tab-reviews true

Libraries such as Radix UI and Headless UI implement this pattern for frameworks and are a good choice when you already use them, and a hand-written component of this size is easy to maintain when you do not.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.