CSS-Only Animated Accordion

Overview

This CodePen demonstrates how we can animate the opening and closing states of an accordion with fancy reveal animation using only CSS. This concept is suitable for creating FAQ sections, Table of Contents, and more.

How does it work?

We cannot transition height or any CSS property from zero to auto. If we want to smoothly expand a collapsed accordion, we could set a max-height and transition the height property to a large value when we expand the section. However, it may not properly work if the content is larger than the max-height.

So, here we create a CSS grid with a grid item. Then we transition the grid-template-rows property from 0fr to 1fr and the grid item transitions to its content height.

I used CSS clip-path and mix-blend-mode to animate the background and text color of the accordion. Each accordion has two pseudo-elements. We know that opacity, clip-path and, visibility are animatable CSS properties. So when the accordion is selected using the :target pseudo-class, we transition the clip-path circle radius to 200% of the ::before pseudo-element. When the accordion is not selected, we do the same with the ::after but this time with a delay. This creates an illusion as it appears to clip from inside.

Since the accordion's title is an anchor element, users can also navigate through the items with their keyboard.

Inspiration

In a recent video, Kevin showed us a way to animate height from zero to auto value. Seeing that, I couldn't resist experimenting with the idea. Then I came up with this CSS-only accordion component and added the reveal animation too!

I would highly recommend watching his video, where he beautifully explains the technique and points out how he discovered it. Also, read Keith J. Grant's post and Nelson Menezes's post on the same topic.