3

It is possible to apply pseudo-class to an child element.

input[type=checkbox] + label {
  color: #ccc;
  font-style: italic;
} 
input[type=checkbox]:checked + label {
  color: #f00;
  font-style: normal;
}

<input type="checkbox" id="ossm" name="ossm"> 
<label for="ossm">CSS is Awesome</label>

What about to apply that pseudo-class to a partent or parents? For example to the DIV Element? How can I write my CSS Code? My inputs are already "checked" at the page load so I need just to add style.

<div>
    <label for="ossm">
        <input type="checkbox" id="ossm" name="ossm" checked>
    </label>
</div>
karadayi
  • 1,919
  • 2
  • 18
  • 30

1 Answers1

5

The current CSS Selectors Level 4 working draft proposes the relational pseudo-class :has(), so this should be possible in the future:

div:has(> label > input[type=checkbox]:checked) {
   /* ... */
}

However, no browser supports this pseudo-class selector as of the time of this writing.

Currently, it is not possible to "select an ancestor element" with CSS alone. For the time being, you will have to keep using the sibling selector or use some JavaScript to listen for change events on the checkbox and select its ancestor element.

Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159
  • @OP if you're okay with a jQuery or vanilla JavaScript solution, just comment and I'll add one to my answer. I didn't add such a solution as it'd seem off-topic on a question without the `javascript` tag. – Fabrício Matté Aug 13 '14 at 06:29
  • Note that while Selectors 4 introduces `:has()` (formerly the subject indicator), [it's still tentatively being excluded from CSS](http://dev.w3.org/csswg/selectors4/#profiles). – BoltClock Aug 13 '14 at 07:49
  • @BoltClock I was unware of that, thanks for the info! Quoting the working draft: "CSS implementations conformant to Selectors Level 4 must use the fast profile for CSS selection." -- so this means that `:has()` will not be available for use in stylesheets? *sigh* That would vastly diminish the usefulness of such a selector. – Fabrício Matté Aug 13 '14 at 08:22
  • 1
    It's not clear if implementations are free to try their hand at implementing `:has()` or if doing so would be nonconformant. Hopefully someone will come up with a better way to allow slow selectors to be used in CSS without causing too much overhead. – BoltClock Aug 13 '14 at 08:30