Pure CSS Toggle (Show/Hide) HTML Element


CSS only toggle (show/hide) HTML DOM element without JavaScript. See demo first. Please click the following to toggle:

There are three HTML elements in the demo:

<label for="element-toggle">&#8803;</label>
<input id="element-toggle" type="checkbox" />
<ul id="toggled-element">
  <li><a href="https://www.google.com/">Google</a></li>
  <li><a href="https://duckduckgo.com/">DuckDuckGo</a></li>
  <li><a href="https://www.ecosia.org/">Ecosia</a></li>
</ul>
  1. A visible HTML label element
  2. A invisible HTML input checkbox element, referenced by the above label element via for attribute.
  3. The element to be toggled. This could be any element, such as div or span, and it is ul element in this demo.

When users click on the visible label element, the invisible input checkbox element becomes checked/unchecked by the click. Then the following CSS rules are used to show or hide the element to be toggled according to whether the checkbox is checked or not.

label[for=element-toggle] {
  cursor: pointer;
}
#element-toggle {
  display: none;
}
#element-toggle:not(:checked) ~ #toggled-element {
  display: none;
}

There are three rules in above CSS code. The last rule is the most important part in this trick. It says if the element with id=element-toggle (i.e., the input checkbox) is not checked, the adjacent element with id=toggled-element (ul element in this case) is hidden. If the input checkbox is checked, this rule is not applied to the ul element, which makes the ul element visible. The last CSS rule shows or hides the element to be toggled according to whether the checkbox is checked or not.

This technique can be used to toggle nav menu in mobile screen [7], and there is no JavaScript code to slow down the speed of the website.


Tested on:

  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]
[2]CSS only menu toggle - no JavaScript required
[3]
[4]
[5]
[6]
[7]CSS Only Bulma Responsive Nav Bar (Navigation Bar)
[8]