Search code examples
htmlcssdrop-down-menu

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 (without using any JavaScript).

Is it possible to create the same dropdown as the one in the example below, in pure CSS, but when clicking an element instead of when hovering over it?

I would prefer to use no JavaScript at all, or - if not possible without JavaScript - as little JavaScript as possible. The items of the drowndown should be clickable themselves.

Example:

.dropdown {
    position: relative;
    display: inline-block;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}
<div class="dropdown" style="float:left;">
  <button class="dropbtn">Left</button>
  <div class="dropdown-content" style="left:0;">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>


Solution

  • 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.