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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11813465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:41:15  来源:igfitidea点击:

CSS sibling selectors (select all siblings)

csscss-selectors

提问by Chad

Usually, I'm good with CSS, but I can't seem to figure this one out. If I have a structure of

通常,我擅长 CSS,但我似乎无法弄清楚这一点。如果我有一个结构

<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 .openclass with CSS? My main issue is that sibling selectors (.open + h2) will only target the h2 immediately following .open.

如何使用.open带有 CSS的类来定位所有同级 h2s ?我的主要问题是同级选择器 ( .open + h2) 将只针对紧随其后的 h2 .open

回答by BoltClock

You can select all the following siblings using ~instead of +:

您可以使用~代替来选择以下所有兄弟姐妹+

.open ~ h2

If you need to select all h2elements that aren't .openwhether they precede or follow .open, there is no sibling combinator for that. You'll need to use :not()instead:

如果您需要选择所有h2不在.open之前或之后的元素,.open则没有同级组合器。您需要:not()改用:

h2:not(.open)

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

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

div > h2:not(.open)

回答by agrublev

I know this isn't a direct answer to your question, but I've found it to be a much more efficient way to select siblings by simply selecting all the children of the parent, and specifying a unique class for the open as you have it there. So the code would be:

我知道这不是您问题的直接答案,但我发现这是一种更有效的选择兄弟姐妹的方法,只需选择父母的所有孩子,并为开放指定一个独特的类它在那里。所以代码将是:

div h2 { } // apply the style for all "siblings" but really children
div h2.open { } // apply the style or cancel styles from the siblings

This works great for me and it doesn't require new css rules or anything special.

这对我很有用,它不需要新的 css 规则或任何特殊的东西。