CSS-only accordion style method to hide or display text (checkbox hack)

CSS

This HTML and CSS are for a very simple open/shut accordion style display.

/* Styles for open and shut or hide and display content in a pane with CSS only */

/* create a container */
#container div {
  position: relative;
}

/* Make an input of type checkbox, and position it absolutely within the relative parent div */
input[type="checkbox"] {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

/* Make the cursor change when the label is moused over */
label {
  cursor: pointer;
}

/* Make the label the full width of the page for usability */
label {
  position: relative;
  display: block;
  }
 
/* Hide the checkbox */
label::before {
  content: "";
  position: absolute;
  }

/* Set #pane to hidden by default / unclicked state */
#pane {
  max-height: 0;
  overflow: hidden;
  transition: min-height 0.4s ease;
}

/* Set checkbox to display content when clicked */
input[type="checkbox"]:checked ~ h2 ~ #pane {
  max-height: max-content;
}

/* Optional */
#container h2 {
	border-bottom: 1px solid black;
}

HTML

<div id="container">

<div>
  <input type="checkbox" id="label1">
  <h2><label for="label1">First Label</label></h2>
  <div id="pane">
    <p>Hide or display this text on click.</p>
  </div>
</div>

<div>
  <input type="checkbox" id="label2">
  <h2><label for="label2">Second Label</label></h2>
  <div id="pane">
    <p>Hide or display this text on click.</p>
  </div>
</div>

</div>

Test it with this jsFiddle

Posted by Jenny Smith

I'm Jenny Smith. I blog about life on the 300+ acres of rolling farmland in Northern Virginia where I live. I like tomatoes, all things Star Trek, watercolor, and reading. I spend most days in the garden fighting deer and groundhogs while trying to find my life's meaning. I'm trying to be like Jesus -- emphasis on the trying.