0

Here is my html :

<div id="blabla" class="control-me">
  <label for="toggle">the label</label>
  <input type="checkbox" id="toggle">
</div>

and my CSS :

.control-me {
  border: #222222;
  background-color: aqua;
}

#toggle:checked ~ .control-me {
  border: #cd0a0a;
  background-color: #cd0a0a;
}

#toggle {
  opacity: 100;
}

This is based on the checkbox hack and neatly summarized in that jsFiddle.

I would expect the div to turn from aqua to red when I check the checkbox but it doesn't.

Why and how to make it work ?

I was pointed to this question automatically but I don't even understand why so I'm asking the same question again.

Chapo
  • 2,196
  • 2
  • 21
  • 46
  • 1
    You can't style the parent of a css selector. You can achieve this by changing the position of the checkbox element in the DOM then use CSS to position it where you want it to appear. Alternatively, you can change the parent elements css using JavaScript when the checkbox is checked. – Matt Budz Oct 07 '20 at 06:56

1 Answers1

0

Your code doesn't work as in your case you're trying to access the parent instead of a sibling.

.control-me {
  border: #222222;
  background-color: aqua;
}

#toggle:checked~.control-me {
  border: #cd0a0a;
  background-color: #cd0a0a;
}

#toggle {
  opacity: 100;
}
<div>
  <input type="checkbox" id="toggle">
  <div id="blabla" class="control-me">
    <label for="toggle">the label</label>
  </div>
</div>

You possibly can't access the parent using CSS alone so it's best to just change the position of your checkbox to make it work on a sibling. Although the question you refereed has many options you can use this approach as per the blog you mentioned.

Black Mamba
  • 8,408
  • 4
  • 52
  • 84