Accordions in CSS

Accordions in CSS

Accordions in CSS

Accordions in CSS is a common UI pattern that allows users to toggle the visibility of content sections. In HTML and CSS, accordions can be implemented using a combination of checkboxes and CSS styling to control their appearance. Here’s an example of how to create an accordion using CSS:

HTML:

				
					<div class="accordion">
  <input type="checkbox" id="accordion-1" name="accordion-checkbox" hidden>
  <label for="accordion-1" class="accordion-header">Section 1</label>
  <div class="accordion-content">
    <p>This is the content for section 1.</p>
  </div>
  	
  <input type="checkbox" id="accordion-2" name="accordion-checkbox" hidden>
  <label for="accordion-2" class="accordion-header">Section 2</label>
  <div class="accordion-content">
    <p>This is the content for section 2.</p>
  </div>
<input type="checkbox" id="accordion-3" name="accordion-checkbox" hidden>
  <label for="accordion-3" class="accordion-header">Section 3</label>
  <div class="accordion-content">
    <p>This is the content for section 3.</p>
  </div></div>

				
			

CSS:

				
					.accordion {
  max-width: 500px;
  margin: 0 auto;
}

.accordion-header {
  display: block;
  padding: 10px;
  background-color: #f1f1f1;
  color: #444;
  font-weight: bold;
  cursor: pointer;
}	

.accordion-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

.accordion-checkbox:checked ~ .accordion-content {
  max-height: 500px;
}

				
			

In this example, we first create a container for the accordion and add a hidden checkbox input for each section. We then create a label element for each section and associate it with its corresponding checkbox using the for attribute.

We use CSS to style the accordion header and content. The header is given a block display, padding, background color, color, font weight, and cursor style. The content is initially hidden with a maximum height of 0 and an overflow of hidden. We add a CSS transition to animate the max-height property when the checkbox is checked.

Finally, we use the :checked pseudo-class to select the accordion content when its corresponding checkbox is checked. We set the max-height property to a large enough value to show all the content.

Join To Get Our Newsletter
Spread the love