Animated Accordion Details Without JS

Animated Accordion Details Without JS

Category: Tips
Last modified on December 14, 2024

Introduction

One of the clear trends in modern web development is the emergence of solutions that enable the implementation of familiar interface elements using native functions. A prime example of such an element is the accordion, often used for creating FAQs.

In this article, I want to share a piece of code that provides all the essential functionality:

  • Smooth animated collapsing and expanding.
  • Automatic closing of other items when a new one is opened.
  • Proper, modern semantics.

The Code

I believe the code is self-explanatory and ready for use in your projects. The only detail requiring further clarification is discussed at the end of this article.

<div class="accordion"> <details name="faq"> <summary>If you were a dog, which breed would you want to be?</summary> </details> <div class="accordion__content"> <div class="accordion__content-body"> <p>Definitely a pug.</p> </div> </div> </div>
.accordion { &__content { display: grid; grid-template-rows: 0fr; transition-duration: .2s; &-body { overflow: hidden; } } details[ open ] + &__content { grid-template-rows: 1fr; } }

Note

The only aspect worth highlighting is the name attribute. This attribute is essential if you want other <details> elements to close automatically when one is opened. Simply assign the same value to all of them:

<div class="accordion"> <details name="faq">...</details> ... </div> <div class="accordion"> <details name="faq">...</details> ... </div> <div class="accordion"> <details name="faq">...</details> ... </div>

If you prefer to allow multiple cards to remain open simultaneously, just omit this attribute!