简体   繁体   English

CSS伪类:选中适用于父母

[英]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? 例如DIV元素? How can I write my CSS Code? 我怎么写我的CSS代码? 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: 当前的CSS Selectors Level 4工作草案提出了关系伪类:has() ,因此将来可能会这样:

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. 目前,单独使用CSS“选择祖先元素”是不可能的。 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. 目前,您必须继续使用兄弟选择器或使用一些JavaScript来侦听复选框上的change事件并选择其祖先元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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