CSS同级选择器(选择所有同级) [英] CSS sibling selectors (select all siblings)
问题描述
通常,我对CSS很好,但是我似乎无法弄清楚这一点.如果我的结构是
Usually, I'm good with CSS, but I can't seem to figure this one out. If I have a structure of
<div>
<h2 class="open">1</h2>
<h2>2</h2>
<h2>3</h2>
<h2>4</h2>
<h2>5</h2>
</div>
如何使用CSS的.open
类来定位所有同级h2?我的主要问题是同级选择器(.open + h2
)仅将紧随.open
之后的h2作为目标.
how can I target all of the sibling h2s using the .open
class with CSS? My main issue is that sibling selectors (.open + h2
) will only target the h2 immediately following .open
.
推荐答案
您可以使用~
而不是+
选择以下所有兄弟姐妹:
You can select all the following siblings using ~
instead of +
:
.open ~ h2
如果需要选择不是.open
的所有h2
元素,无论它们是在.open
之前还是之后,都没有同级组合器.您需要使用:not()
代替:
If you need to select all h2
elements that aren't .open
whether they precede or follow .open
, there is no sibling combinator for that. You'll need to use :not()
instead:
h2:not(.open)
如果需要将选择范围限制为div
个父母,则可以选择使用子组合器:
Optionally with a child combinator if you need to limit the selection to div
parents:
div > h2:not(.open)
这篇关于CSS同级选择器(选择所有同级)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!