DEV Community

Vadim Filimonov
Vadim Filimonov

Posted on

Accordion on pure CSS

In this article I will try to tell you how to create an accordion using only styles.

Layout

<input class="question-input" id="question" type="checkbox">
<label class="question-label" for="question">
 Click me?
</label>
<div class="answer">
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque officia ipsum quam sequi! Ratione dolorem ad quam maxime a facere voluptate? Nulla dignissimos iure dolorum, a fuga excepturi sunt modi!
</div>
Enter fullscreen mode Exit fullscreen mode

Instead of adding an additional class, we will focus on the :checked pseudo-class of the input element.

Styles

.question-input {
display: none;
}

.answer {
height: 0;
overflow: hidden;
transition: 0.5s;
}

.question-input:checked + .question-label + .answer {
height: auto;
padding: 10px 0;
}
Enter fullscreen mode Exit fullscreen mode

Piece by piece

Hide the checkbox

.question-input {
display: none;
}
Enter fullscreen mode Exit fullscreen mode

It's better to do it through the visually hidden pattern, but it's enough for a tutorial example.

Setting the answer styles

.answer {
 // reset the height
height: 0;
 // hide the block
overflow: hidden;
 // set the duration of the animation
transition: 0.5s;
}
Enter fullscreen mode Exit fullscreen mode

And describe the rules for the unfolded accordion

.question-input:checked + .question-label + .answer {
height: auto;
padding: 10px 0;
}
Enter fullscreen mode Exit fullscreen mode

A couple of words about the animation - it is crooked:

This is due to the fact that height: auto; can not be animated through transition, you need to know the exact value. That's why, as a hack, we use padding.

If you're happy with the animation - consider yourself lucky.

See my codepen for the current demo.

Discussion (0)