Properly implementing tabs requires a comprehensive set of ARIA attributes to ensure accessibility. These ARIA attributes not only facilitate styling but also enhance accessibility:
role="tablist"
- Defines the container for tab headers.
role="tab"
- Indicates a tab element, which should be a
button
and a direct child ofrole="tablist"
. The selected tab is identified witharia-selected="true"
orfalse
accordingly. role="tabpanel"
- Used for the contents that are switched by the tab buttons. Inactive content should be
hidden (
hidden
).
In addition to the aforementioned styling attributes, it's essential to include aria-controls
, aria-labelledby
, and id
attributes for tabs and tab panels to ensure
proper support for screen readers.
Tabs
The sleek silver sedan hummed softly as it glided down the winding mountain road, its headlights piercing through the darkness.
The bustling city bus rumbled along, filled with a diverse array of passengers, each lost in their own thoughts amidst the rhythmic sway of the journey.
The vibrant red bike leaned against the old oak tree, its tires still warm from the afternoon ride, while the sun cast long shadows across the quiet suburban street.
If there is an element following the last
role="tabpanel"
, a gap is automatically
added.<article role="presentation">
<h2>Tabs</h2>
<div role="tablist">
<button aria-controls="car" aria-selected="true" id="tab-car" role="tab">
Car
</button>
<button aria-controls="bus" aria-selected="false" id="tab-bus" role="tab" tabindex="-1">
Bus
</button>
<button aria-controls="bike" aria-selected="false" id="tab-bike" role="tab" tabindex="-1">
Bike
</button>
</div>
<div aria-labelledby="tab-car" id="car" role="tabpanel">
The sleek silver sedan hummed softly as it glided down the winding
mountain road, its headlights piercing through the darkness.
</div>
<div aria-labelledby="tab-bus" id="bus" role="tabpanel" hidden>
The bustling city bus rumbled along, filled with a diverse array
of passengers, each lost in their own thoughts amidst the rhythmic
sway of the journey.
</div>
<div aria-labelledby="tab-bike" id="bike" role="tabpanel" hidden>
The vibrant red bike leaned against the old oak tree, its tires
still warm from the afternoon ride, while the sun cast long shadows
across the quiet suburban street.
</div>
<div>If there is a following element after last <code>role="tabpanel"</code> gap is added automatically.</div>
</article>