CSS only menu toggle - no JavaScript required

A lot of menus require JavaScript to toggle its visibility. However, it's very simple to accomplish the same task without any JavaScript by using a simple label and checkbox along with the :checked pseudo-class.

Demo

The code below is for a very bare-bone example, add your own styles, use it for an off-canvas navigation or for any other element that you just want to toggle between two states.

<label for="menu-toggle">Click me to toggle menu</label>  
<input type="checkbox" id="menu-toggle"/>  
<ul id="menu">  
  <li><a href="#">First link</a></li>
  <li><a href="#">Second link</a></li>
  <li><a href="#">Third link</a></li>
</ul>  
label {  
  cursor: pointer;
}
#menu-toggle {
  display: none; /* hide the checkbox */
}
#menu {
  display: none;
}
#menu-toggle:checked + #menu {
  display: block;
}

The way this works is that the label is associated with the checkbox via the for and the id so that when you click on the label, it toggles the checkbox on and off. In the CSS, we have a rule that only applies when the checkbox is checked. If you wanted the menu to be visible by default, you simply have to specify that the checkbox is checked initially.

Browser support is almost everything on both desktop and mobile, however it will only work from Internet Explorer 9 and up.

comments powered by Disqus