· css · 1 min read

Accordion by CSS grid

No script. No complex.

No script. No complex.

Background

In developing nested accordions, a common challenge arises ensuring that the parent accordion accurately calculates its body height when a child accordion expands. Traditionally, implementing this functionality with JavaScript introduces significant complexity to the code.

However, there is a straightforward solution that eliminates the need for JavaScript entirely using only CSS. The key to this approach lies in utilizing CSS Grid. Initially, the accordion body should be set with grid-template-rows: 0fr;. Upon toggling, this should change to grid-template-rows: 1fr;. This simple adjustment is all that is required.

Example

Hover me!

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Code Explanation

<div class="group">
  <div class="">Hover me!</div>
  <div class="grid grid-rows-[0fr] group-hover:grid-rows-[1fr] transition-all">
    <div class="overflow-hidden">
      <p>Lorem Ipsum is simply dummy text.</p>
    </div>
  </div>
</div>

In this example, the accordion using tailwindcss, expands on hover, which dynamically adjusts the grid row size. This method provides a clean and efficient way to create interactive elements without the overhead of JavaScript.

Share:
Back to Blog