Managing state with vanilla CSS

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 checkboxes. As for browser support, this has been supported since IE9 in 2011.

  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:

<!-- HTML -->
<label for="question">Click me!</label>
<input id="question" class="checkbox" type="checkbox" />
<div class="answer">Surprise!</div>
/* CSS */
.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!

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.