Skip to content

Search

Accessible tabs, with CSS that reads the state

A11yJavaScriptCSS

The ARIA tabs pattern looks small, but it hides a dozen decisions. Here is the markup, the keyboard code and a way of writing CSS that can't drift from what screen readers are told, with a position on every contested point.

by
10 min read

How hard can a row of buttons with one visible panel be? Hard enough that practitioners still disagree on parts of it, and one screen reader bug around tabs has been open since 2018.

TL;DR

Use <button> tabs with automatic activation and a roving tabindex, and style every state through its ARIA attribute instead of a class. Hide panels with hidden="until-found" so find in page still works, and make the visible panel focusable.

Markup and state

Tabs fit related content that shares one place on the page: the plans of a pricing table, the settings of one object. They don’t fit unrelated content. TetraLogical lists “unrelated sections of content (use separate pages instead)” under when not to use them. And if every “tab” loads its own page, we’re looking at site navigation: a <nav> with links and aria-current="page", no script needed.

The contract

tabs.html
<h2 id="plans">Pricing plans</h2>
<div role="tablist" aria-labelledby="plans">
  <button type="button" role="tab" id="t1" aria-controls="p1" aria-selected="true">Free</button>
  <button type="button" role="tab" id="t2" aria-controls="p2" aria-selected="false" tabindex="-1">Pro</button>
</div>
<div role="tabpanel" id="p1" aria-labelledby="t1" tabindex="0">…</div>
<div role="tabpanel" id="p2" aria-labelledby="t2" hidden="until-found">…</div>

Every attribute has a job. The tablist gets a name from a visible heading. Each tab carries aria-selected (exactly one is true) and points to its panel with aria-controls. Unselected tabs get tabindex="-1": this roving tabindex keeps one tab in the Tab sequence and leaves the rest to the arrow keys. Each tabpanel points back with aria-labelledby. That one isn’t optional: in WAI-ARIA 1.2 a tabpanel’s name is required and comes from the author.

Selecting a tab is an action. It changes what this page shows, it doesn’t take you anywhere. A <button> brings Enter and Space for free and leaves the URL and the history alone.

Links are allowed too, and TetraLogical and Heydon Pickering build their tabs from same-page links, so everything still works without JavaScript. That’s a fair reason. The cost is a preventDefault() on every click and a hand-written Space handler, because links only activate on Enter.

Style from state

I style tabs only through the attributes above, never through classes like .is-active:

tabs.css
[role='tab'][aria-selected='true'] {
  font-weight: 700;
  border-color: currentColor;
}

[role='tab']:focus-visible {
  outline: 2px solid;
  outline-offset: 2px;
}

[role='tabpanel']:not([hidden]) {
  display: grid;
  gap: 0.5rem;
  padding: 1rem;
}

If the script forgets to update aria-selected, the visual state breaks too. The bug is then visible to everyone, not only to screen reader users. The CSS becomes a test of the ARIA.

Note the :not([hidden]). Writing [role="tabpanel"] { display: grid } shows every panel, because an author rule beats the browser’s own [hidden] { display: none }.

Warning: Forced colours drop shadows

In forced colours mode, box-shadow and text-shadow compute to none and backgrounds are replaced. A selected state drawn only with a shadow or a background disappears. A border survives, which is why TetraLogical draws “a thicker top border instead”.

Keyboard

Automatic activation

With automatic activation, moving focus to a tab also selects it. With manual activation, the arrows only move focus and Enter or Space selects. I recommend automatic, and so does the APG, with one condition:

It is recommended that tabs activate automatically when they receive focus as long as their associated tab panels are displayed without noticeable latency.

— WAI-ARIA Authoring Practices: Tabs pattern

If a panel has to load its content first, every arrow press waits for it. That’s where I switch to manual. Two more reasons came up while building both versions. With manual activation, focus and selection drift apart: arrow to “Team” without activating it, press Tab, and you land in the “Free” panel that is still shown. And the workaround for the screen reader bug below only works with automatic activation.

Key Action
→ / ← Next or previous tab, wrapping at the ends
Home / End First or last tab
Tab Leaves the tablist, next stop is the shown panel
↑ / ↓ Nothing in a horizontal tablist, the page can scroll

Call preventDefault() only for the keys you handle, never for Tab. And let the click handler call focus() itself: Safari doesn’t focus a button when it’s clicked, so without it the tab stop and the keyboard position go separate ways.

Vertical tabs

With aria-orientation="vertical", ↓ and ↑ take over. Without the attribute a tablist is horizontal. I read the orientation inside the key handler, not once at start-up, so a responsive layout can switch it:

tabs.js
const vertical = tablist.ariaOrientation === 'vertical';
const [prevKey, nextKey] = vertical ? ['ArrowUp', 'ArrowDown'] : ['ArrowLeft', 'ArrowRight'];

The layout follows the attribute, not the other way round. :has(> [role="tablist"][aria-orientation="vertical"]) puts the tabs beside the panels.

What ← and → should do in a vertical tablist isn’t specified, and a question about it on the APG mailing list in 2023 got no answer. I leave them inert, mirroring the APG rule for ↑ and ↓ in horizontal tablists. The cost: if you guess the wrong axis, nothing tells you. Right-to-left layouts are open as well, in an APG issue filed in July 2020.

Edge cases

Should the panel be focusable?

This is where practitioners disagree most. TetraLogical keeps panels out of the Tab sequence. Pickering gives them tabindex="-1" and moves focus in with ↓. The APG asks for a focusable panel when “the first element with content is not focusable”.

I go one step further than the APG: the visible panel always gets tabindex="0". Tab then always lands on the panel. In my test with Safari, VoiceOver announced the panel name “Free”. Without tabindex, the text-only panel was skipped and focus jumped to the next link.

The cost is one extra Tab on panels that start with a link, and a focus ring on a container that does nothing. TetraLogical avoids that stop on purpose. I accept it for the same behaviour in every panel. Use :focus-visible for that ring, not :focus-within, or it stays on while a control inside the panel has focus.

Find in page with hidden=“until-found”

With plain hidden, find in page can’t reach text in an unselected panel, and a link to it goes nowhere. hidden="until-found" fixes both. When the browser finds a match inside, it fires beforematch on the panel, removes hidden and scrolls. Our job is to select the matching tab in that event, without moving focus: you searched, you didn’t navigate to the tablist.

Chrome, Edge and Firefox 148 support it. Safari falls back to plain hidden, as the HTML spec intends, so the tabs work and only search and deep links don’t.

Three details surprised me. A panel hidden this way isn’t display: none. It gets content-visibility: hidden and keeps an empty box, so it can still take focus. I checked in Chrome 155: with tabindex="0" on a hidden panel, focus() lands on it. So tabindex="0" has to move with the selection.

The empty box also stays in Chrome’s accessibility tree, as an empty tabpanel named after its tab. With plain hidden it’s gone. aria-hidden="true" on the hidden panels takes them out again, and find in page still reaches them. The script removes it from the selected panel.

And the box claims a row in a vertical grid layout, which pushes the shown panel below the tabs:

tabs.css
/* never set display or visibility on it, that breaks find in page */
[role='tabpanel'][hidden='until-found' i] {
  position: absolute;
}

The browse-mode bug

Scott O’Hara reported in 2018 that NVDA and JAWS in browse mode put focus on the wrong tab:

If a screen reader were not running, a tab with a -1 tabindex would not receive keyboard focus.

— Scott O’Hara: Trouble Tabbing To Tabs

The bug reports for both screen readers are still open. In the NVDA issue, a developer explains why: the screen reader can’t tell elements that are only focusable by script from keyboard-focusable ones. O’Hara suggests a stopgap, a focusin listener that sends focus to the selected tab. According to O’Hara, NVDA then behaves, and JAWS focuses the right tab without announcing it.

I recommend the stopgap with automatic activation only. With manual activation the arrows focus unselected tabs on purpose, and the listener sends focus straight back. I confirmed that in the browser, without a screen reader. NVDA and JAWS I haven’t tested.

What I tested, and the full script

  • VoiceOver with Safari on macOS: Tab into a text-only panel, with and without tabindex="0".
  • Chrome 155: whether a hidden="until-found" panel with tabindex="0" takes focus, with plain hidden as the control, and whether it stays in the accessibility tree.
  • Keyboard: 20 automated tests in Chrome for the script below, covering automatic activation, vertical orientation and until-found.
  • Not tested: NVDA, JAWS, Firefox, and VoiceOver’s announcements for manual activation and vertical tablists.

Everything above in one script:

tabs.js
for (const tablist of document.querySelectorAll('[role="tablist"]')) {
  const tabs = [...tablist.querySelectorAll('[role="tab"]')];
  const panelOf = (tab) => document.getElementById(tab.getAttribute('aria-controls'));

  function select(tab, { focus = true } = {}) {
    for (const t of tabs) {
      const selected = t === tab;
      const panel = panelOf(t);
      t.ariaSelected = String(selected);
      if (selected) t.removeAttribute('tabindex');
      else t.tabIndex = -1;
      panel.hidden = selected ? false : 'until-found';
      if (selected) panel.removeAttribute('aria-hidden');
      else panel.ariaHidden = 'true'; // Chrome keeps until-found panels in the accessibility tree
      if (selected) panel.tabIndex = 0;
      else panel.removeAttribute('tabindex');
    }
    if (focus) tab.focus();
  }

  tablist.addEventListener('click', (e) => {
    const tab = e.target.closest('[role="tab"]');
    if (tab) select(tab);
  });

  tablist.addEventListener('keydown', (e) => {
    const i = tabs.indexOf(e.target.closest('[role="tab"]'));
    if (i === -1) return;
    const vertical = tablist.ariaOrientation === 'vertical';
    const [prevKey, nextKey] = vertical ? ['ArrowUp', 'ArrowDown'] : ['ArrowLeft', 'ArrowRight'];
    const last = tabs.length - 1;
    const next = {
      [nextKey]: i === last ? 0 : i + 1,
      [prevKey]: i === 0 ? last : i - 1,
      Home: 0,
      End: last,
    }[e.key];
    if (next === undefined) return;
    e.preventDefault();
    select(tabs[next]);
  });

  // Find in page or a fragment link revealed a hidden panel: sync the tabs, keep focus.
  tablist.parentElement.addEventListener('beforematch', (e) => {
    const panel = e.target.closest('[role="tabpanel"]');
    const tab = panel && tabs.find((t) => panelOf(t) === panel);
    if (tab) select(tab, { focus: false });
  });

  // Stopgap for NVDA and JAWS browse mode (O'Hara 2018). Automatic activation only.
  tablist.addEventListener('focusin', (e) => {
    const selected = tabs.find((t) => t.ariaSelected === 'true');
    if (e.target !== selected) selected.focus();
  });
}

Conclusion

Most of the tabs pattern is settled. Panel focus, link tabs and the arrow keys in vertical tablists aren’t, and the browse-mode bug shows that markup alone can’t fix everything. If you test with NVDA or JAWS: does the stopgap still matter in 2026?

Further reading

Written by

Oliver Scheffler

I’ve been building websites for 25 years and write here about frontend, accessibility and performance – mostly about things I struggled with myself.

Animating the <details> element without JavaScript

CSSA11yPerformance

With interpolate-size and ::details-content, the <details> element opens and closes smoothly. Browsers without support open it instantly, as they always have.

6 min read