英文:
How can I select the ::before of a sibling element with css?
问题
我已经使用以下HTML创建了一个复选框:
<div class="chkbox">
<input id="accept-filter" type="checkbox" class="filter-handler" checked="">
<label for="accept-filter">
::before
<span class="label-txt">我接受条款</span>
</label>
</div>
我想要样式化::before
伪元素,但只有在复选框被选中时才这样做。
我已成功使用:has
选择器来实现:
.chkbox:has(.filter-handler:checked) label::before
然而,在Firefox中这不起作用(似乎不支持:has
选择器)。
我希望有一种方法可以使用+
兄弟选择器来实现,但以下方法似乎不起作用(jsfiddle链接):
.filter-handler:checked + label::before
是否有一种方法可以实现这个效果?
英文:
I have created a checkbox using the following HTML:
<div class="chkbox">
<input id="accept-filter" type="checkbox" class="filter-handler" checked="">
<label for="accept-filter">
::before
<span class="label-txt">I accept the terms</span>
</label>
</div>
I would like to style the ::before
pseudo-element, but only when the checkbox is checked.
I have done this successfully using the :has
selector:
.chkbox:has(.filter-handler:checked) label::before
However this doesn't work in Firefox (it seems the :has
selector isn't supported).
I was hoping there was a way to do this by using the +
sibling selector, but the following doesn't seem to work (jsfiddle):
.filter-handler:checked + label::before
Is there a way to do this?
答案1
得分: 2
你所使用的方法是有效的。你可以使用'+'选择器来实现这个功能。
它适用于类名和标签名,如下所示:
.filter-handler:checked + .filter-label::before
或者
.filter-handler:checked + label::before
找到下面的代码:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.filter-handler:checked + .filter-label::before {
content: 'Selected';
display: inline-block;
background-color: blue;
color: '#fff';
}
<!-- language: lang-html -->
<div class="chkbox">
<input id="accept-filter" type="checkbox" class="filter-handler" checked="">
<label for="accept-filter" class="filter-label">
<span class="label-txt">I accept the terms</span>
</label>
</div>
<!-- end snippet -->
英文:
The approach you used will work. You can use the '+' selector to do this.
It works with a class name as well as a tag name as follows:
.filter-handler:checked + .filter-label::before
or
.filter-handler:checked + label::before
Find the below code
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.filter-handler:checked + .filter-label::before {
content: 'Selected';
display: inline-block;
background-color: blue;
color: '#fff';
}
<!-- language: lang-html -->
<div class="chkbox">
<input id="accept-filter" type="checkbox" class="filter-handler" checked="">
<label for="accept-filter" class="filter-label">
<span class="label-txt">I accept the terms</span>
</label>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论