CSS 兄弟选择器(选择所有兄弟)

2022-01-10 00:00:00 css-selectors css

通常,我擅长 CSS,但我似乎无法弄清楚这一点.如果我的结构是

<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.

解决方案

你可以使用 ~ 代替 + 选择以下所有兄弟:

.open ~ h2

如果您需要选择所有不是 .openh2 元素,无论它们在 .open 之前还是之后,都没有同级组合器.你需要使用 :not() 代替:

h2:not(.open)

如果您需要将选择限制为 div 父母,则可以选择使用子组合器:

div >h2:not(.open)

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>

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

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)

Optionally with a child combinator if you need to limit the selection to div parents:

div > h2:not(.open)

相关文章