Tabs based on the details tag Example

Tabs based on the details tag

Back to Tutorial

Using the <details> tag to create tabs

The details tag

Imagine an accordion-like element with native keyboard support that doesn't require javascript for control.

Enter the details tag.

The details tag

This is a details tag with content

The details tag gives us a simple accordion with no scripts—that's great! But it feels like it could be something more...imagine if it could do tabs.

What about tabs?

Tabs and accordions work in technically the same way, although tabs typically require a shared parent container and containers to build out the tabs and content separate from each other.

Interactivity is another difference: the ways accordions or tabs are toggled. With accordions it's common to be able to open and close them individually, but with tabs there must always be one, and only one, open.

At first glance there doesn't seem to be a way to make this work. The structure isn't right. The layout isn't right. The functionality isn't quite right. But each of those problems can be solved if we look a bit closer.

CSS trickery

With a little help from the display: contents; property, we can transform a group of discrete details tags with tab and content area elements as children, into a group of the tab and content area elements from all the details elements mixed together.

Say you had 3 small buckets of red and blue balls. The buckets can interact with each other or bang together, but the balls inside each bucket can't interact with the balls from the other buckets.

You could think of what we are doing like pouring all of the small buckets into a larger bucket. Now all of the balls can interact with each other and we can organize them by color in the bigger bucket. With display: contents; it's as if the details tag isn't there at all—at least visually.

Now that all the tab and content area elements can interact with each other in the flow of the page, we can use display: flex; and order to make the tabs flow nicely but also be separate from the content area.

And that's what you see here! Open up the inspector and have a look.

UX patches with javascript

So you might have thought we could get by without any JS, but we need it a little. Luckily it's the type of script that you can write once and reuse without reconfiguration.

The default functionality of the details tab means that it can be toggled open or closed. That's not what we want for tabs. Each details tag must be manually closed and then another opened. We want a tab to stay open and then close when another is picked.

By watching for attribute changes and blocking keyboard and mouse input from toggling a details tab when a tab is open, we can emulate the expected tab behavior.

Then it's just a matter of toggling the sibling details tags when another is selected.