Accordion Animation with CSS

Accordion Animation with CSS

Create an accordion web component with this CSS trick!

The most common solution to implementing an accordion is by manually overriding the max-height property with JavaScript.

There’s a simpler solution. The HTML should include a simple button element with text wrapped by a div. Keep in mind that the content within the container can be any type of element(s).

<button id="button">Toggle</button>

<div id="container" class="container">
    <span class="content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit
        esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia
        deserunt mollit anim id est laborum.
    </span>
</div>

Then, add the CSS styles to transition on the container div when an additional class, show, is added.

.container {
  display: grid;
  grid-template-rows: 0fr;
  overflow: hidden;
  transition: grid-template-rows 0.5s;
}

.container.show {
  grid-template-rows: 1fr;
}

.content {
  min-height: 0;
}

The container element has the grid-template-rows as 0fr as default - representing the minimized view. When the class show is added, the grid-template-rows is overridden to 1fr triggering the expansion animation.

💡
min-height: 0; overrides the smallest height of text set by the DOM to allow for the minimized view.

Lastly, use JavaScript to toggle the show class each time the button is clicked.

document.getElementById('button').addEventListener('click', () => {
  document.getElementById('container').classList.toggle('show');
});

Voilà! A sliding animation has been successfully created with minimal JavaScript!


Thanks to Web Dev Simplified for this YouTube short.