details
Does it work without JavaScript?
Yes, this accordion uses the
HTMLDetailsElement
element.
One at a time
Give the
details
elements a
name
attribute to create an accordion.
<details name="accordion" class="group w-full border-b px-4 pt-4 pb-2">
<summary class="link flex list-none items-center justify-between gap-8 py-2">
<span>Does it work without JavaScript?</span>
<!-- chevron-down -->
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="size-5 transition group-open:rotate-180"
>
<path
fill-rule="evenodd"
d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z"
clip-rule="evenodd"
/>
</svg>
</summary>
<div>
Yes, this accordion uses the
<code>HTMLDetailsElement</code>
element.
</div>
</details>
<details name="accordion" class="group w-full border-b px-4 pt-4 pb-2">
<summary class="link flex list-none items-center justify-between gap-8 py-2">
<span>One at a time</span>
<!-- chevron-down -->
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="size-5 transition group-open:rotate-180"
>
<path
fill-rule="evenodd"
d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z"
clip-rule="evenodd"
/>
</svg>
</summary>
<div>
Give the
<code>details</code>
elements a
<code>name</code>
attribute to create an accordion.
</div>
</details>
<style>
details {
@media (prefers-reduced-motion: no-preference) {
interpolate-size: allow-keywords;
}
/* for safari */
summary::-webkit-details-marker {
display: none;
}
&::details-content {
transition:
content-visibility 300ms allow-discrete,
block-size 300ms;
block-size: 0;
overflow-y: clip;
}
&[open]::details-content {
block-size: auto;
}
}
</style>
Overview
You can animate the <details>
element with discrete transitions the interpolate-size
property. This example was adapted from this article from Adam Argyle.
Add the same name
attribute to each details element if you would like to have only one open at a time. Here, name="accordion"
is applied to each element creating an accordion component. If you are making an accordion component using a UI framework, be sure to generate a unique name
for each component mounted on the page.