Accordion with CSS3

Today we’ll experiment some more with the adjacent and general sibling combinator and the :checked pseudo-class. Using hidden inputs and labels, we will create an accordion that will animate the content areas on opening and closing.

There are many variations of CSS-only accordions around, most of which are implemented using the :target pseudo-class. The problem with using :target is that we can’t really close the content areas again or have multiple sections open at the same time. By using hidden checkboxes, we can control the opening and closing. Alternatively, we can also use radio buttons if only one section should be open at a time.

So, let start!

Please note: the result of this tutorial will only work as intended in browsers that support the CSS3 properties in use.

The Markup

We will be going through an example that uses checkboxes where one content section is open by default (the input needs to be ‘checked’). Everything will be wrapped in a container with the class ac-container. For each item, we will have a checkbox, a label and an article which is the content section of that item:

Note that we need to give each input an ID which we will then use in the for attribute of the label. We need this in order to check the checkbox when clicking on the label.

Each article will have a class that will help us determine to which height we it to expand to. (Optimally, we could use ‘auto’ as the expanded height value, but unfortunately it will not animate like that.)

Let’s have a look at the style.

The CSS

I will omit all the vendor prefixes, but you will, of course, find them in the files.

Let’s define a width for the accordion and center it:

.ac-container{
width: 400px;
margin: 10px auto 30px auto;
}

Next, we’ll make the labels appear as clickable buttons by giving them some slick background gradient. With multiple box shadows, we’ll create a subtle border and an inset effect. We’ll also set the z-index to 20, to make sure it will be on top of the content section:

The content area will have an initial height of 0px and any overflow will be hidden. We’ll add a transition for the height and for the box shadow. The transition that we are adding here will act upon “closing” the item. We define another transition for the selected item. So, we can basically control the two behaviors by doing this. As you can see, we will make the closing a bit faster than the opening.

Mary Lou (Manoela Ilic) is a freelance web designer and developer with a passion for interaction design. She studied Cognitive Science and Computational Logic and has a weakness for the smell of freshly ground peppercorns.