Using <details> to Show/Hide Content

The <details> element is a simple way to create an accordion without JavaScript, CSS trickery, or any other non-semantic methods. It's also fully compliant with accessibility standards.

This pen shows some examples of what can be achieved with some pretty simple CSS.

I also have some JavaScript in this pen. The JS allows only one <details> element to be open at a time. Without this, each <details> isn't aware of any others on the page. JavaScript isn't needed if you don't want this extra functionality. All JS is used for is checking the open attribute and toggling it as needed.

I'm the first header. Click me and I'll open!

I'm an <h2> inside of the collapsed element

Here's a <p> tag with some regular copy. We can also include elements like an image or other kinds of rich media.

Placeholder
This should have a styled arrow instead of the default triangle

When we click on one of these elements, <details> will become <details open>. We then can use CSS to pick up on that and change the arrow based on the state.

Depending on what browsers we're supporting, we may have to account for a webkit vendor prefix. But both versions are pretty simple. I left it in the simplest form for the sake of the demo, but depending on the image we pick, we may have a flicker as the second image loads. We can offset this by preloading the image, putting the SVG directly into the CSS, or using something like a sprite.

What about browser support?

Browser support is excellent . The only holdouts are the pre-Chromium versions of Edge and all versions of Internet Explorer.

Why is this better than using an EventListener?
  • Using <details> is semantic.
  • Using <details> is fully accessible. Try tabbing through the bullet points and pushing enter. We are fully accessible with no extra work!
  • Using <details> requires no JavaScript. As a result, it is interactive on immediately on page load.
Opening this dropdown will include an animation

The text will slide in from the left.