Burt67 Burt67 - 1 year ago 83
CSS Question

CSS Selectors not working

So I have a question about the css selectors in reference to my design.

I'm trying to fiddle around with how you can manipulate check-boxes through css by using multiple selectors such as "+", "~", etc to perform an event when the checkbox is either checked or unchecked.

I'm confused as to why this doesn't work, or by using "~" instead since from my understanding "+" selects elements matching it directly after the first element while "~" selects every element that comes after the prior element. This is my first time playing around with it so I'm not the best...but I'm trying to wrap my head around it. Does "element":checked not count as a reference point when stringing multiple selectors? I left two tried on the jsfiddle.

While this is intended to be a navigation menu later, I just, for the time being, left it like this to get a hang of selectors first.


<div id="container">
<input type="checkbox" id="navigation_drawer">
<label for="navigation_drawer" id="drawer_open"></label>
<label for="navigation_drawer" id="drawer_close"></label>
<nav id="navigation">
<li id="home_page"><a href="#">Home</a></li>
<li id="about_page"><a href="#">About</a></li>


position: absolute;
top: 2;
right: 0;
margin-right: 1rem;
background-image: url('http://i.imgur.com/Nxafddw.png');
background-image: no-repeat;
width: 35px;
height: 23px;


#navigation_drawer:checked + #container #navigation{

#navigation_drawer:checked + container #navigation{


Edit: Man you guys are harsh xD Yes, I did make some mistakes copying and pasting this into here and in my code itself when I was changing it around. My fault. Here is an updated fiddle of the original problem for reference. I updated the HTML/CSS here as well. Thank you Pete for the updated fiddle. I would give it to you but since it's a comment instead of a reply I'll accept the other person's since it's another way as well. Thanks :D


Answer Source

Your code doesn't work because the + (Adjacent Sibling Selector) selects the element that immediately follows it. In this case, the immediate element after your checkbox is your #drawer_open label, not the nav.

Adjacent Sibling Selector This is referred to as an adjacent selector or next-sibling selector. It will select only the specified element that immediately follows the former specified element.

You seem to have incorrect indentation for your labels, so perhaps that made you think the nav is the direct sibling. In any event, you'd need to use the General Sibling Selector (~).

The correct code to achieve what you want would be:

#navigation_drawer:checked ~ #navigation{
  background-color: red;

Fixed fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download