0

I'm trying to create a toggle for mobile menu, but the :checked selector doesn't seem to be working.

Here is the Code:

#toggleMenuToggle:checked .nav-css {
  display: none;
}
<label class="desktop-hidden menuToggle" for="toggleMenuToggle">MENU</label>
<input type="checkbox" name="toggleMenuToggle" id="toggleMenuToggle">
<ul id="dropdown-nav" class="nav-css">
  <li class="n1 current">
    <a class="n1">Test</a>
  </li>
</ul>

Shouldn't the <ul> have it's display set to none when my checkbox is checked?

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126

3 Answers3

6

Try the following solution:

#toggleMenuToggle:checked ~ .nav-css {
  display: none;
}
<label class="desktop-hidden menuToggle" for="toggleMenuToggle">MENU</label>
<input type="checkbox" name="toggleMenuToggle" id="toggleMenuToggle">
<ul id="dropdown-nav" class="nav-css">
  <li class="n1 current">
    <a class="n1">Test</a>
  </li>
</ul>

Explanation: With your solution the .nav-css element have to be a child of the checkbox (#toggleMenuToggle). But in your case the .nav-css is the following element of the checkbox, so you have to use the ~.

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
2

You want to use the + or ~ selector. The + selector selects the adjacent sibling while the ~ selector selects all sibling elements. In this case it does not actually matter which one you choose.

#toggleMenuToggle:checked + .nav-css {
  display: none;
}

For a nice explanation of the selectors see https://stackoverflow.com/a/26282459/6430127

Community
  • 1
  • 1
Till Arnold
  • 561
  • 2
  • 11
0

The problem with your css is that .nav-css is not a child of #toggleMenuToggle.

Try the following:

#toggleMenuToggle:checked ~ .nav-css {
    display: block
}

The ~ Selects every .nav-css element that are preceded by a #toggleMenuToggle element

SKeurentjes
  • 1,848
  • 12
  • 18