简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM