Skip to main content

How to Build An Accordion using CSS

Build Accordion using CSS

Today we are going to make Accordion using CSS in two different ways: using Checkbox and using Radio. Both accordions can be opened using a Checkbox, while the Radio accordion closes another when one is opened. Our tutorial is designed to be easy-to-follow, with step-by-step instructions and clear explanations. We'll guide you through each step of the process, from structuring your HTML to styling your accordion with CSS.


Open in new tab

HTML Code for Checkbox based Accordion:


<div class="accordion-tab">
  <input id="tab-1" type="checkbox">
  <label for="tab-1">Accordion 1</label>
  <div class="content">
    <img src="https://try.siddharthkamra.in/example/northern-lights.jpg">Northern Lights
  </div>
</div>
<!-- Second Accordion of Checkbox -->
<div class="accordion-tab">
  <input id="tab-2" type="checkbox">
  <label for="tab-2">Accordion 2</label>
  <div class="content">
    <img src="https://try.siddharthkamra.in/example/sunset.jpg">Sunset
  </div>
</div>

HTML Code for Radio based Accordion:


<div class="accordion-tab">
  <input id="tab-3" name="tab-radio" type="radio">
  <label for="tab-3">Accordion 1</label>
  <div class="content">
    <img src="https://try.siddharthkamra.in/example/northern-lights.jpg">Northern Lights
  </div>
</div>
<!-- Second Accordion of Radio -->
<div class="accordion-tab">
  <input id="tab-4" name="tab-radio" type="radio">
  <label for="tab-4">Accordion 2</label>
  <div class="content">
    <img src="https://try.siddharthkamra.in/example/sunset.jpg">Sunset
  </div>
</div>

This CSS works for both:

* {
  box-sizing: border-box;
}
.accordion-tab input,
.accordion-tab .content {
  display: none;
}
.accordion-tab input:checked ~ .content {
  display: block;
}
.accordion-tab {
  margin-bottom: 10px;
}
.accordion-tab label {
  display: block;
  padding: 10px;
  font-weight: 700;
  color: #fff;
  background: #064adb;
  cursor: pointer;
}
.accordion-tab .content {
  padding: 10px;
  background: #ccdef9;
  border-radius: 0px 0px 5px 5px; /* Optional */
}
.accordion-tab label {
  position: relative;
}
.accordion-tab label::after {
  display: block;
  content: "\25b6";
  position: absolute;
  right: 10px;
  top: 10px;
  transition: all 0.4s;
}
.accordion-tab input:checked ~ label::after {
  transform: rotate(90deg);
}
.accordion-tab .content img {
  width: 100%;
  border-radius: 5px;
}
.accordion-tab .content {
  text-align: center;
  font-size: 24px;
  font-weight: 700;
}

You have successfully learned creating two types of Accordions using HTML and CSS. If you have any doubt. Leave the comments below. Thank you!

Comments