Interactive state with CSS

April 08, 2018

If you need to create an expandable, collapsible interface – like an accordion FAQ section or dropdown menu – and you don’t want to use JavaScript, you can use vanilla CSS to achieve a similar result.

I'm a reactive menu written in vanilla CSS!

To make this work, we can take advantage of a few vanilla HTML/CSS concepts:

  1. clicking a <label> can focus an <input>
  2. CSS’s :checked selector can sense checked checkboxes1
  3. CSS’s + selector can interact with an element that comes after another

If we put all three of those together, we’ve created a stateful interface:

<label for="question">Click me!</label>
<input id="question" class="checkbox" type="checkbox" />
<div class="answer">Surprise!</div>
.answer {
	display: none;

.checkbox:checked + .answer {
	display: block;

That’s all there is to it. I’m not sure that there’s a real reason to use this over JavaScript, but I figure that there’s an edge case where someone will need to use it. If nothing else, it’s a great way to flex your CSS muscles. Enjoy!

  1. As for browser support, this has been supported since IE9 in 2011. ↩︎

Get the articles and announcements that I never post publicly: