Build an Accordion without JavaScript

In the pursuit of web performance, we are all looking to come up with clever solutions to make our website load faster. One way many of us do this is coming up with and stealing ( which in this case, the latter is more appropriate ) ways of writing less JavaScript.

Many websites I work on include an FAQ section, are nine times out of ten I end up building some form of accordion. But recently I saw a method of building a mobile menu without the use of JavaScript, and I wondered if I could use the same method to build an accordion.

The process is relatively simple, rather than having a button with an ID, which you then target in JavaScript to show content on click, you can simply use label and input elements.

The above pen really simply demonstrates how we can achieve this.

We use the label to use as the question, and we also include a checkbox.
The checkbox is hidden from view. When we click on the label, it checks the input and then we can use this to display the answer.

You’ll notice here we use the general sibling combinator or ~.
For more information on this, I wrote some more information here.

The above example was very simple, how about a styled up version?

After searching on Google, I know others have also used this solution in the past, so it may not be new to you, but it would interesting to get your thoughts.

As a note on browser compatibility, the only thing you have to really consider is the general sibling selector, information can be found here.

Let me know your thoughts.




Front-End & WordPress Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Michael Weaver

Michael Weaver

Front-End & WordPress Developer

More from Medium

Input Character Limit with counter using HTML, CSS, and Javascript

Weather app javascript | Weather app using HTML CSS Javascript

Simple weather API Project Javascript | Weather App Javascript

Building front-end Javascript, CSS and HTML. Joke Generator.