Animated CSS Accordions
The details and summary HTML element are a modern way to create accordions. On top of that, we can add small bit of CSS to animate the open and closed state.
It will be accessible, lean, and quick to create. Also, no javascript will be necessary to control states by adding classes to the DOM.
Here’s a very simple example of how the stock accordion works:
<details>
<summary>Tab</summary>
Tab content that's hidden by default.
</details>
You can add the open attribute to have an accordion open on page load.
<details open>
<summary>Tab</summary>
Now you can see this content on load.
</details>
Now to the animation, we’ll need to use interpolate-size to animate height changes. This isn’t fully supported in all browsers at the time of writing this. But the good news is nothing will break if so, it’ll just not animate.
The finishing steps are applying css transitions to shadow dom elements for block-size, content-visibility, and opacity.
details::details-content {
block-size: 0;
opacity: 0;
transition:
block-size 0.3s ease,
content-visibility 0.3s ease,
opacity 0.3s ease;
transition-behavior: allow-discrete;
}
details[open]::details-content {
block-size: auto;
opacity: 1;
}
That will make an open and close state buttery smooth! Check out the demo:
See the Pen Multi Select by Glenn Weatherson (@gweatherson) on CodePen.