Pure CSS Accordion (Collapsible Content)


CSS only accordion (collapsible content) implementation. The accordion here is similar to the accordion example in Bootstrap Collapse. Click the title of following panels to see the demo.

Content Body #1
Content Body #2
Content Body #3

The basic technique is the same as Pure CSS Tab Panel [2]. We need:

  • Visible HTML label elements, which is the title of panels.
  • Invisible HTML input radio elements, referenced by the label elements. The value of name attribute of these elements must be the same.
  • Panel contents (body), invisible in the beginning.

When users click on the visible label elements, the corresponding input radio element is checked. We use CSS3 :checked selector to select corresponding panel content, and make the selected panel body content visible.

The complete source code is as follows:

HTML:

<input type="radio" id="panel-1" name="accordion-select">
<input type="radio" id="panel-2" name="accordion-select">
<input type="radio" id="panel-3" name="accordion-select">
<div class="panel">
  <div class="panel-title">
    <label for="panel-1">Title #1</label>
  </div>
  <div class="panel-body body-1">
    Content Body #1
  </div>
</div>
<div class="panel">
  <div class="panel-title">
    <label for="panel-2">Title #2</label>
  </div>
  <div class="panel-body body-2">
    Content Body #2
  </div>
</div>
<div class="panel">
  <div class="panel-title">
    <label for="panel-3">Title #3</label>
  </div>
  <div class="panel-body body-3">
    Content Body #3
  </div>
</div>

CSS:

.panel {
  margin-bottom: 1rem;
  border: 1px solid #ccc;
}
.panel-title {
  font-weight: bold;
  background-color: #ccc;
  padding: 0.01em 16px;
}
.panel-title > label {
  cursor: pointer;
}
.panel-body {
  padding: 0.01em 16px;
  display: none;
}

input[name="accordion-select"] {
  display: none;
}

/* the magic */
#panel-1:checked ~ .panel > .body-1,
#panel-2:checked ~ .panel > .body-2,
#panel-3:checked ~ .panel > .body-3 {
  display: block;
}

The magic is in last rule. We use :checked and general sibling selector (~) to make the user-selected panel body content visible.


Tested on:

  • Chromium Version 58.0.3029.110 Built on Ubuntu , running on Ubuntu 17.04 (64-bit)

References:

[1][Vue.js] Accordion (Collapsible Content)
[2]Pure CSS Tab Panel