-1

I was trying to make a css only clicking navigation system using checkboxes and labels. I never played much around labels and checkboxes other than what they're meant to be used for by the w3c. This is the minimal code I managed to put this into:

.bar{
  list-style-type:none;
}
.bar ul{
  display:none;
}
.bar input[type=checkbox]{
  display:none;
}
label:hover{
    cursor:pointer;
}
input[type=checkbox]:checked + label{
  color:blue;
}
input[type=checkbox]:checked + ul{
  display:inline;
}
<nav>
  <ul class=bar>
    <li>
      <input type=checkbox id=1><label for=1>about</label>
      <ul>
        <li>us
        <li>you
        <li>cheese
      </ul>
   </ul>
</nav>

By clicking on "about" you can see that the label successfully turns blue, but the ul right below it in the code doesn't get it's inline display, it stays with a display of none as specified on the 4th line of css, which I used to hide the tabs by default.

What did I do wrong?

towc
  • 1,983
  • 2
  • 22
  • 36
  • Use general sibling combinator `~` instead. Like so `input[type=checkbox]:checked ~ ul` or adjacent sibling combinator `+` two times: `input[type=checkbox]:checked + label + ul` – Hashem Qolami Sep 27 '14 at 08:08
  • See: http://stackoverflow.com/questions/10782054/what-does-the-css-tilde-squiggle-twiddle-selector-do/10782072#10782072 and http://stackoverflow.com/questions/3382078/what-does-mean-in-css/3382096#3382096 – Hashem Qolami Sep 27 '14 at 08:15

2 Answers2

2

Try this code --> JSfiddle

Remember that + works only if ul is first sibling of your input. In your case first sibling is label so it doesn't work with ul. To get this work simply use something like this :

input[type=checkbox]:checked + label + ul{
    display:inline;
}
Kamil
  • 1,987
  • 16
  • 14
1

You need to use the ~ operator in the last css rule instead of +; as shown below. See The CSS Tricks Article for more details on that.

.bar{
  list-style-type:none;
}
.bar ul{
  display:none;
}
.bar input[type=checkbox]{
  display:none;
}
label:hover{
    cursor:pointer;
}
input[type=checkbox]:checked + label{
  color:blue;
}
input[type=checkbox]:checked ~ ul{
  display:inline;
}
<nav>
  <ul class=bar>
    <li>
      <input type=checkbox id=1><label for=1>about</label>
      <ul>
        <li>us
        <li>you
        <li>cheese
      </ul>
   </ul>
</nav>

Hope that helps :)

user3459110
  • 6,961
  • 3
  • 26
  • 34