:checked on changing class/selector attributes not working

Hi all!
Play around with class/selector-modifications thru clicked checkboxes.
example
It is not really working, please see example. When clicking on 1st square - it works as a toggler to check the checkbox - only the 2nd square turns green. Both are div and have same class. Moreover the body background shall change color.
So far I dont know jscript, not finished css yet, but saw examples where you can toggle menus just with css this way.
Actually want to toggle a nav-bar on my test-website thru click on hamburger menu, but nothing changes, :checked command not executed in browser. So even this littel square example not working for manipulating classes and selectors.
Could you please help me understanding what is going on?
Thank you! :slight_smile:

The first div isn’t a direct sibling of the input so you’ll need to add a selector to target it:

input:checked ~ .box, 
input:checked + label > .box {   /* ~ div .box not working at all*/
  background: green;
}

Also, I just want to make you aware that this checkbox pattern is not the way you would implement a hamburger menu as it is not accessible. A proper hamburger menu requires JS. I understand if you haven’t started JS then that isn’t an option yet, which is fine, no harm in playing around with the skills you currently have. But please do not consider this a legitimate method for creating a hamburger method.

As said, the first selector is a General sibling combinator.

In the second selector, you are trying to select a parent element. That is not how selectors work, you can not go up from the starting selector only down (children/descendants) or stay at the same level (siblings). The only way you can make that work is with the :has() selector which is still very new and not supported in all browsers.

<body>
   <label id="navbar-toggler" for="toggle">
      <!-- sibling -->
      <input type="checkbox" id="toggle">
      <div class="box">div inside label. Click me to toggle checkbox.</div>
   </label>
   <br>
   <div class="box">div outside label</div>
</body>
input:checked ~ .box {
   background: green;
}

body:has(input:checked) {
   background: yellow;
}

body:has(input:checked) .box {
   background: green;
}

Oh oh, this is tough. Thank you for your explanations, but I am not quite sure I got it.
It means the 1st selector and the 2nd have to be on the same “level” in the code? The first square is nested in sth else and that is why its not working, right?
Or the 2nd element shall be a direct child of 1st, then its working as well.

I know I have to learn JS later, but for now I just wanted to understand how this trick is working for hamburger menus.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.