For decades, animating an accordion was a mess. JavaScript scrollHeight calculations, magic max-height values, janky transitions.
2024 brought the solution:
.accordion-content {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 0.4s ease;
}
.accordion-content.open {
grid-template-rows: 1fr;
}
The child needs overflow: hidden. That's it. The grid track smoothly transitions from zero to its content height. No JavaScript required for the animation.
Accessibility
-
aria-expanded="true/false"on headers (mandatory) -
role="region"on content panels - Keyboard support: Enter/Space to toggle
The Toggle Logic
The most common bug: clicking an already-open panel causes a flash. Solution — track the isOpen state before closing everything:
const isOpen = content.classList.contains('open');
this.headers.forEach(h => close(h));
if (!isOpen) open(header);
This component is part of Web Component Dictionary v2.0 — 83 components, ¥9.99.
Live demo: wdsega.github.io/web-components
Top comments (0)