Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS pseudo-class :checked apply to parents

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>
like image 784
karadayi Avatar asked Mar 11 '26 10:03

karadayi


1 Answers

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.

like image 65
Fabrício Matté Avatar answered Mar 13 '26 03:03

Fabrício Matté



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!