David David - 16 days ago 9
CSS Question

Dropdown menu for mobile devices

I'm looking for a way to do it, or a simple "You have to use JavaScript."

Is it possible to make a pure CSS dropdown menu for mobile devices, or do I have to use JavaScript?

I tried using the :focus pseudo, but I can't click the links, even though the menu opens (It closes before the link in clicked).
The :active pseudo doesn't even work half way.

So is there some trick to doing this, or do I need to use JavaScript?

Answer

Yes, the :checked pseudoclass works in all major mobile browsers.

The way you can do this is the following:

<input class="dropdowninput" type="checkbox" id="dropdownbox1"/>
<div class="dropdownbox">
    <label for="dropdownbox1">Open dropdown</label>
    <ul class="dropdown">
        <li>...</li><li>etc</li>
    </ul>
</div>

with CSS:

.dropdowninput, .dropdown {display:none;}
.dropdowninput:checked + .dropdownbox .dropdown {display:block;}

That way, your dropdown ul will only show up when the checkbox is checked. The disadvantage might be that when the dropdown is opened, it will only close if it's manually closed by the user.

You could also use :hover which is probably the effect you're looking for:

<div class="dropdown">
Open
    <ul>
        <li>asdf</li>
        <li>foo</li>
    </ul>
  </div>

With CSS:

.dropdown ul {display:none;}
.dropdown:hover ul {display:block;}

this simple jsbin works for me on my Chrome on Android.

This works because the nested ul is still hovered on when clicking anything within the dropdown, while the "triggering" label element is not focused anymore when clicking something inside. Also, the :active probably doesn't work because of how mobile browsers work, but I wouldn't really know that to be honest.