CSS-dropdowns

Here is a nice tip shared by Danny Markov from Tutorialzine: it’s a simple, yet a great technique for creating dropdowns with CSS only. To create dropdowns you only need the checkbox HTML element and some smart usage of CSS selectors. In the end you will have a nice dropdown wihout a single line of JavaScript.

Here is how it looks like:

See the Pen Pure CSS dropdown by designhooks (@designhooks) on CodePen.

HTML structure

There is nothing special here, all the elements are in standard HTML which we use every day. However, there is a requirement: the input element has to be first, followed by label and ul. This is quite important and you will understand this a little bit later, when we’ll review the CSS.

<div class="dropdown">
    <input id="checkbox_toggle" type="checkbox" />
    <label for="checkbox_toggle">Click to Expand</label>
    <ul>
      <li><a href="#">Link One</a> </li>
      <li><a href="#">Link Two</a></li>
      <li><a href="#">Link Three</a></li>
      <li><a href="#">Link Four</a></li>
    </ul>
</div>

As you can see, the HTML markup consists of:

  • The div which acts as a container for everything
  • The input type=checkbox which we need for its checked/unchecked property. It will be hidden all the time
  • The label which will be used to toggle the input and act as a trigger for the dropdown
  • The ul is simply a list we want to be visible when the dropdown is extended. You can use any other element instead

The hack

The checkbox element is needed for its checked state, which we can style using the :checked CSS pseudo selector. Checking and unchecking it is done by clicking the label, which is a basic browser feature. We first hide the checkbox:

input[type=checkbox] {
    display: none;
}

The ul should be hidden by default – it’s the dropdown menu which is visible when the dropdown is extended.

ul {
    display: none;
}

Here comes the hack. If we combine the :checked selector with the general siblings selector (~) we can change CSS properties of elements that follow the checkbox. That’s why we needed the input element to be first, before the ul in the DOM tree.

input[type=checkbox]:checked ~ ul {
    display: block
}

The CSS snippet above will show the unordered list only when the checkbox is checked. Hope you enjoyed this nice tip and will find it useful for your projects.

Feel free to download the full source code of this example on tutorialzine.

1 thought on “How to create pure CSS dropdowns without JavaScript

Comments are closed.

You may also like