Home >Web Front-end >CSS Tutorial >Native HTML: Accordion Revisited
Six years ago, I explored the native elements to create accessible accordions. Since then, the web platform has evolved, introducing exciting new features like exclusive open behaviour and smooth animations for these elements.
In this article, we'll revisit
The element acting as the clickable label. This makes it easy to create disclosure widgets with minimal effort.
Here’s a simple example:
<details> <summary>Read more</summary> Some text to be hidden. </details>
Clicking the summary toggles the visibility of the associated content. No JavaScript required!
To mimic traditional accordion behaviour, where only one section is open at a time, you can use the name attribute on your
<details name="exclusive"> <summary>Section 1</summary> <p>Content for section 1.</p> </details> <details name="exclusive"> <summary>Section 2</summary> <p>Content for section 2.</p> </details>
This behaviour is native and works seamlessly in modern browsers!
To make the opening and closing transitions smoother, we can use modern CSS properties like interpolate-size and transition-behavior.
Here’s a complete example of the CSS used in the demo:
details { interpolate-size: allow-keywords; overflow: clip; margin-top: 0.125em; border: 1px solid #dddddd; background: #ffffff; color: #333333; border-radius: 3px; } details summary { display: block; cursor: pointer; position: relative; padding: 0.5em 0.5em 0.5em 0.7em; background: #ededed; color: #2b2b2b; border-radius: 3px 3px 0 0; } details:not([open]) summary:hover, details:not([open]) summary:focus { background: #f6f6f6; color: #454545; } details[open] summary { outline: 1px solid #003eff; background: #007fff; color: #ffffff; } details[open]::details-content { height: auto; } details::details-content { height: 0; overflow-y: clip; transition: content-visibility 475ms allow-discrete, height 475ms; } details main { padding: 1em 2.2em; }
Here’s the full implementation:
For browsers without support, the animations gracefully fall back, and the accordion remains functional without the smooth transitions.
The elements, combined with modern CSS, provide a lightweight and accessible solution for creating interactive accordions. These new enhancements make them even more appealing for modern web projects. Try out the demo and give your accordions a fresh, polished look!
Thanks so much for reading. If you'd like to connect with me outside of Dev here are my twitter, bsky and linkedin come say hi ?
The above is the detailed content of Native HTML: Accordion Revisited. For more information, please follow other related articles on the PHP Chinese website!