How To Create An Accordion With Only HTML And CSS

Kafui KumahKafui Kumah
2 min read

Introduction

Accordions are used on many websites all over the internet. While working on a personal project, I wanted to explore how to create one. That led me to use Javascript and a bunch of JQuery. But that was complex.
However, HTML can simply do the job! Here's how I built an accordion with only HTML and CSS in a project I recently worked on recently.

Required HTML tags

The required HTML tags for building an accordion are the <details> and <summary> tags.
Code Structure:

<details>
   <summary>Title of Accordion</summary>
    Accordion Content Goes Here
</details>

Adding content to the accordion

Below the summary tag, we can add any type of content with different HTML tags including paragraphs, buttons, Inputs, divs, links, images, lists, and many others.
Let's look at an example:

<details>
    <summary> <h3>My Account</h3> </summary>
    <p>My Profile</p>
    <p>Switch Account</p>
    <p>Report a Problem</p>
    <p>Settings</p>
    <p>Log Out</p>
</details>

The Output(Interactive):

My Account

My Profile

Switch Account

Report a Problem

Settings

Log Out

Styling your accordion

Styling your HTML accordion is just like styling regular text-based HTML tags. You can apply colors, animations, borders, corner-radius, hover-styles, shadows, and so on.sdf

<style>
details {
    width: 250px;
    padding: 1rem;
    border-radius: 8px;
    background: white;
    box-shadow: 4px 4px 3px rgba(0,0,0,0.15);
}
summary {
    cursor: pointer;
}
summary h1 {
    display: inline;
    margin-left: 1rem;
    font-size: 1.25rem;
}
details p {
    margin-left: 1.75rem;
    opacity: 0.7;
}
</style>

The Output when the above styling is applied:

I hope you found this useful. Be sure to let me know if you have any questions or suggestions as to how to improve this. If you have a solution on how to remove the arrow as well, I will be glad to hear it.

In my next article, I will write a similar article on how to animate the accordion with only HTML and CSS.

Till then, I wish you all the best. Happy Coding!

0
Subscribe to my newsletter

Read articles from Kafui Kumah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kafui Kumah
Kafui Kumah

I am a software developer and user interface designer from Ghana. I am all about building badass software with a focus on scalability and performance. When I am not coding up a storm, you can find me exploring new technologies and sharing my knowledge about them. Currently building PaperCard, and writing all the lessons I learn along the way. I am open to collaborations, mentoring juniors, supporting tech communities, speaking at tech events, and most importantly, job opportunities. Domain interests: Education, Human resource, energy, insurance, SaaS, Healthcare, AI, Socio-Economic Causes, Energy. I am looking for an opportunity to make an impact.