I admit, because of using newer CSS, namely the
:checked pseudo selector, you alienate your older IE audience. But that can be fixed by including Selectivizr. So you have your increased performance and ease of use in newer browsers with a working version in IE. The first thing you will need is the HTML.
Now the HTML for this particular accordion is a little more complicated than some. That is because we are utilizing radio buttons to perform the toggle on click action. But do not fear, it only means one extra element that is actually set to
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
I have only added two content panes here, but you can add as many as you require. As you can see, we have a simple unordered list with a class applied to it (
<ul class='accordion'>). Each list item contains a label, input and div. The label is where you store your title and the div is where you put your content. You can style all of this however you want. Just adapt my CSS that I will show you in a second.
When adding more items you must remember to update the
for attribute on the label and the
id of the radio input. Otherwise you will click one and six will show. You can also specify a content pane to be open by default by adding
checked='checked' to its radio button, just like I have done in the HTML above. Other than that you can just copy and paste to your hearts content.
Now here is the code that makes the accordion work. I have added comments to help you out, but you may still find it a bit confusing. If you do just utilize it in your project via copy and paste first, then keep tweaking it until you know what does what. I believe that it is one of the best ways to understand some confusing code. Style it up, add some transitions. Maybe even adapt it to work horizontally. Just don’t say “bah! that looks too hard, I give up”. Just experiment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
So this CSS first adds some basic styles, so we can actually distinguish between content panes, and then adds the radio button based functionality. This relies heavily on the adjacent sibling selector (
+). So in the last selector we are saying: “any div with a class of ‘content’ that is under a checked radio button that is under a label should be displayed”. See, that’s not so bad is it, and that is the most complicated line!
The main question is, does it work? Well yes, yes it does. And here is an example. Here is a fiddle too, just in case you want to play about with the code as well as the accordion itself.