In this guide, you’ll learn a step-by-step approach to creating a CSS-only accordion.
Building Basic Accordion Using HTML Only
Styling the Accordion
You can style the accordion by adjusting the background-color, border-radius, margin, padding, etc.
Output:
There are two popular methods to create a custom CSS-only accordion. You can either use checkboxes or radio buttons; we’ll explain both methods.
Using the Checkbox Method
The Checkbox Method uses checkbox as the input type. Whenever a user selects a tab, they mark the checkbox and it opens. You can open multiple tabs simultaneously using the Checkbox Method, similar to how you can mark more than one checkbox inside an HTML form.
HTML
General CSS
Apply the basic CSS to the body.
Styling the Accordion
First, hide the checkboxes by modifying the input.
Now, style the accordion. You can add an ::after pseudo-element for the + sign. You can refer to a Character Entity Reference Chart and use any Entity Conversion Calculator to find the CSS Value of a Numeric Value. Here, the CSS Value of + is \002B.
Now, let’s add functionality to the accordion using adjacent and attribute selectors. Here, \2013 is CSS Value for –, the Numeric Value representing –.
Output:
Using the Radio Button Method
The Radio Button Method has an input type set to radio. Whenever the user clicks on a tab, the hidden radio button corresponding to that tab opens. When you click on the next tab, the previous tab closes instantly. You can only open one tab at a time using the Radio Button Method.
HTML
CSS
Copy the above CSS of the Checkbox Method as both methods differ from structural point-of-view only. You might notice that there’s one tab open all the time. This happens because you can’t unmark radio buttons like checkboxes. To accomplish this, add the below CSS code to a “Close All” radio button without any description.
Output:
Keep Experimenting and Add Animations
There’s a simple logic behind accordions: when you click on a menu, its hidden content will appear. Since you now know how to create an accordion, it’s high time to implement and experiment with your learning. You can build horizontal accordions to enhance the design, especially when displaying images. Experiment with the code by adjusting the transition effect using keyframe animations.