CSS sibling selectors (select all siblings)(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
如果您需要选择所有不是 .open
的 h2
元素,无论它们在 .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)
这篇关于CSS 兄弟选择器(选择所有兄弟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CSS 兄弟选择器(选择所有兄弟)


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01