NoLoJS logo

Accordion - Animate Open/Close

With a little CSS you can animate the open/close states of the details content.

Demo

Initially closed, click to animate open

This content is initially hidden, but animates open when the summary is clicked.
Click again to animate it closed.

HTML

<!-- Animate the open/close states via CSS. -->
<details>
  <summary>Initially closed, click to <em>animate</em> open</summary>
  <p>This content is initially hidden, but <em>animates open</em> when the summary is clicked.<br>Click again to animate it closed.</p>
</details>

CSS

details {
  interpolate-size: allow-keywords; /* Allows animation between numeric and text values; in this case block-size: 0 --> auto; */
  &::details-content {
    block-size: 0; /* Initial state is 0 height */
    overflow: hidden; /* Prevent content margins from being visible while closed, and contents from being visible during animation */
    @media (prefers-reduced-motion: no-preference) { /* Be nice to others */
      transition: all 0.25s ease-in;
      transition-behavior: allow-discrete; /* Switch between numeric and text value will happen at 50% */
    }
  }
  &[open]::details-content {
    block-size: auto; /* Open state is 100% height */
  }
}

JS

No JS required.

Baseline

[`details`](https://webstatus.dev/features/details) [`details-content`](https://webstatus.dev/features/details-content) [`content-visibility`](https://webstatus.dev/features/content-visibility) [`transition-behavior`](https://webstatus.dev/features/transition-behavior) [`interpolate-size`](https://webstatus.dev/features/interpolate-size)

CodePen

See the Pen on CodePen.