Back To Tutorials
Pure CSS Accordion
Intermediatechallenge
In this challenge, you will create an interactive accordion using only HTML and CSS. The accordion should allow users to expand and collapse content sections by clicking on a header. No JavaScript is allowed for the functionality—CSS transitions and pseudo-classes will handle the interactive behavior. Focus on styling and smooth transitions for a clean and responsive design.
Instructions:
HTML Structure:
- Create multiple sections for the accordion.
- Each section should have a clickable header (e.g., an
<h3>
tag) and a corresponding content area (e.g., a<div>
).
CSS Styling:
- Use CSS
:checked
,:focus
, or:target
pseudo-classes to manage the accordion’s open/close behavior. - Ensure only one accordion section can be open at a time.
- Style the accordion for smooth open/close transitions using the
max-height
property andtransition
.
Bonus:
- Add custom styling to headers when the accordion section is open (e.g., change color, add icons).
- Make sure the design is responsive for mobile
Solution
html
<div class="accordion">
<input type="radio" id="section1" name="accordion" checked>
<label for="section1">Section 1</label>
<div class="content">
<p>This is the content of Section 1.</p>
</div>
<input type="radio" id="section2" name="accordion">
<label for="section2">Section 2</label>
<div class="content">
<p>This is the content of Section 2.</p>
</div>
<input type="radio" id="section3" name="accordion">
<label for="section3">Section 3</label>
<div class="content">
<p>This is the content of Section 3.</p>
</div>
</div>
css
.accordion {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
input[type="radio"] {
display: none;
}
label {
display: block;
padding: 15px;
background-color: #f1f1f1;
cursor: pointer;
font-weight: bold;
margin: 5px 0;
}
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
background-color: #f9f9f9;
padding: 0 15px;
border-left: 3px solid #007bff;
}
.content p {
margin: 15px 0;
}
input[type="radio"]:checked + label + .content {
max-height: 100px; /* Adjust this based on content */
}
input[type="radio"]:checked + label {
background-color: #007bff;
color: white;
}