1

Here's my HTML setup:

<div class="form-item">
    <input type="checkbox" id="my-check">
</div>
<div class="form-item">
    <label for="my-check">I'm a checkbox</label>
</div>

Is there any way in all the world of CSS to style that label based on whether or not the checkbox is checked? (Without changing the current HTML structure?)

Pete
  • 7,289
  • 10
  • 39
  • 63
  • This is why I don't understand why they removed the reference combinator. I remember the WG saying something along the lines of "the author can just change their HTML". I say screw that. Why does this stuff have to depend on the structure. What is so wrong with `label:has(/for/ input[type=checkbox]:checked)`. – BoltClock Sep 26 '15 at 05:16
  • Talking about `:has()`, we can solve this problem using just that without a reference combinator: `.form-item:has(> input[type=checkbox]:checked) + .form-item > label` But again you have to make assumptions about the HTML structure, and you can't always do that. – BoltClock Sep 26 '15 at 05:26

1 Answers1

3

Unfortunately, you cannot use CSS to style your label based on the state of your checkbox without changing your HTML. As of now, CSS selectors support child selectors and sibling selectors, but no selectors to style the child of one element based on the child of another element. You can find the whole list of CSS element combinators at: http://www.w3.org/TR/css3-selectors/#combinators.

BurningLights
  • 2,387
  • 1
  • 15
  • 22
  • Selectors 4 solves this using a pseudo-class to save the need for adding a bunch of new combinators that essentially function as the opposites of existing ones. See sections "Subject of a selector" and "A potential solution" in my answer [here](http://stackoverflow.com/questions/28708741/how-do-i-select-an-element-based-on-the-state-of-another-element-in-the-page-wit/28793064#28793064). – BoltClock Sep 26 '15 at 05:30