0

Style element that is not next to checkbox or label when checkbox is checked.

For example please see the code snippet below. I would like to make the text within div3 red when the #trigger checkbox is checked. I want to use pure css, no jQuery. The only way I can get it to work is if I move the checkbox above div3.

#trigger:checked+.div1 + .div2 > .div3 {
  color: red;
}
<input id="trigger" type="checkbox">
<div class="div1">
    <label for="trigger">
      CHECKBOX LABEL
    </label>
  </div>
  
  
  <div class="div2">
    <div class="div3">ABCD</div>
  </div>
Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • It's working perfectly, it's your expectations that are wrong. See the duplicate post for details about the next-sibling/adjacent-sibling (`+`) combinator. – David Thomas Aug 03 '18 at 19:38
  • If you can't change the structure of your HTML you can't do what you want with CSS alone as there's no parent selector. – j08691 Aug 03 '18 at 19:39
  • this is where the "cascading" part of CSS comes into play -- .div3 isn't below #trigger ... it's a (i guess) cousin (element ^ parent -> sibling - child). The adjacent sibling selector ( https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors ) would work on ` – Doug Aug 03 '18 at 19:42
  • @Doug so is there any selector that could make it possible or is + and changing the html structure my only option? – Blake Rivell Aug 03 '18 at 19:44
  • Not in any way that I am aware of -- your best bet would be to change the structure or add in some JS to detect the change on #trigger and then do something to .div3 – Doug Aug 03 '18 at 19:45
  • @Doug I actually figured out with a small sacrafice which is fine. Moved the input to the outside of everything and then used a double plus. Does this make sense? Please see my updated sample. – Blake Rivell Aug 03 '18 at 19:50
  • Sounds like a good fix -- happy coding. – Doug Aug 03 '18 at 19:51

0 Answers0