Cover Image for CSS Accordion
198 views

CSS Accordion

Sure! An accordion is a popular UI component that allows you to toggle the visibility of content sections. Each section typically consists of a header and a content area. When the header is clicked, the corresponding content area expands or collapses. Let’s create a simple CSS-only accordion:

HTML:

<div class="accordion">
  <div class="section">
    <input type="checkbox" id="section1" class="accordion-checkbox">
    <label for="section1" class="accordion-label">Section 1</label>
    <div class="content">
      Content of Section 1
    </div>
  </div>

  <div class="section">
    <input type="checkbox" id="section2" class="accordion-checkbox">
    <label for="section2" class="accordion-label">Section 2</label>
    <div class="content">
      Content of Section 2
    </div>
  </div>

  <!-- Add more sections as needed -->
</div>

CSS:

/* Optional: Add some styles to make it look better */
.accordion {
  font-family: Arial, sans-serif;
  width: 300px;
  margin: 20px auto;
}

.section {
  border: 1px solid #ccc;
  margin-bottom: 5px;
}

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

.content {
  padding: 10px;
  display: none;
}

/* Handle checkbox states to show/hide the content */
.accordion-checkbox {
  display: none;
}

.accordion-checkbox:checked ~ .content {
  display: block;
}

In this example, we create a simple accordion using HTML and CSS. Each section consists of an input checkbox (hidden) and a label. The label acts as the header for the section, and when clicked, it triggers the checkbox state to expand or collapse the content area.

The content areas are initially hidden using display: none, and the CSS rule .accordion-checkbox:checked ~ .content targets the adjacent .content element that follows a checked checkbox, displaying it when the checkbox is checked.

You can add more sections to the accordion by duplicating the HTML structure of each section. Customize the styles (e.g., colors, padding, fonts) to match your desired design.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS