Skip to content Skip to sidebar Skip to footer

Pure CSS Clickable Dropdown?

This tutorial explains how to use the :hover pseudo-class to style HTML elements on hover and how to how create a dropdown when hovering over a particular element in pure CSS (with

Solution 1:

Here you are using a hidden checkbox, and showing the menu when it is "checked".

/*hide the inputs/checkmarks and submenu*/
input, ul.submenu {
  display: none;
}

/*position the label*/
label {
  position: relative;
  display: block;
  cursor: pointer;
}

/*show the submenu when input is checked*/
input:checked~ul.submenu {
  display: block;
}
<input id="check01" type="checkbox" name="menu" />
<label for="check01">Menu</label>
<ul class="submenu">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
</ul>

Taken from this Codepen and simplified.


Solution 2:

Use radio buttons and sibling selectors.

This differs from checkboxes in that it will automatically close the open menu item when a different one is clicked.

.menu ul,
.menu input,
.menu .closer,
.menu input:checked~.opener {
  display: none;
}

.menu input:checked~ul,
.menu input:checked~.closer {
  display: block;
}
<ul class="menu">
  <li>
    <input type="radio" name="menuopt" id="drop1" />
    <label class="opener" for="drop1">Parent item 1</label>
    <label class="closer" for="dropclose">Parent item 1</label>
    <ul>
      <li><a href="">Menu item 1</a></li>
      <li><a href="">Menu item 2</a></li>
      <li><a href="">Menu item 3</a></li>
    </ul>
  </li>
  <li>
    <input type="radio" name="menuopt" id="drop2" />
    <label class="opener" for="drop2">Parent item 2</label>
    <label class="closer" for="dropclose">Parent item 2</label>
    <ul>
      <li><a href="">Menu item 1</a></li>
      <li><a href="">Menu item 2</a></li>
      <li><a href="">Menu item 3</a></li>
      <li><a href="">Menu item 4</a></li>
      <li><a href="">Menu item 5</a></li>
    </ul>
    <input type="radio" name="menuopt" id="dropclose" />
  </li>
</ul>

View on jsFiddle


Post a Comment for "Pure CSS Clickable Dropdown?"