How to Create an Accordion using HTML CSS JAVASCRIPT

Shuaib Oseni
2 min readMay 11, 2020

--

Hi internet friends,

in this tutorial , i’m going to walk you through on how you can create a simple accordion, using HTML CSS & Javascript.

gentlemen shall we?

Accordion:

The accordion is a graphical control element comprising a vertically stacked list of items, such as labels or thumbnails. Each item can be “expanded” or “collapsed” to reveal the content associated with that item. There can be zero expanded items, exactly one, or more than one item expanded at a time, depending on the configuration.

Accordion is simply grouping of elements in content.

HTML Setup:

For the HTML part, we are going to be needing a couple of buttons and div’s..

<button class="accordion">
Click Me!
</button>
<div class="panel">
<h2>Your content goes here</h2>
<p>this should be fun...</p>
</div>

<button class="accordion">
Click Me!
</button>
<div class="panel">
<h2>Your content goes here</h2>
<p>this should be fun...</p>
</div>

<button class="accordion">
Click Me!
</button>
<div class="panel">
<h2>Your content goes here</h2>
<p>this should be fun...</p>
</div>

CSS:

body{
background-color:blue;
}
button.accordion{
border:none;
outline:none;
width:100%;
background-color:transparent;
text-align:left;
color:#fff;
cursor:pointer;
padding:10px;
margin: 4px 0;
}
button:hover{
background-color:grey;
}
button.accordion.active{
background-color:grey;
color:#fff;
border-radius: 4px 4px 0 0;
}
div.panel{
background:white;
border-radius: 0 0 4px 4px;
overflow: hidden;
opacity: 0;
max-height: 0;
}
div.panel.show{
opacity: 1;
max-height:500px;
}

JS

let accordions = document.querySelectorAll("button.accordion");for( let i = 0; i < accordions.length; i++){
accordions[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}

Click on the buttons , you should have the following result:

There you go, accordion using HTML CSS & JS..

Thanks for reading, i hope this helps in your project. You can follow me on twitter

Here’s a link to the code on codepen..

--

--

Shuaib Oseni
Shuaib Oseni

No responses yet