相邻兄弟组合器
相邻兄弟组合器 (+) 分隔两个选择器,仅当第二个元素紧跟在第一个元素之后,并且两者都是同一父 element 的子元素时,才匹配第二个元素。
css
/* Paragraphs that come immediately after any image */
img + p {
font-weight: bold;
}
语法
css
/* The white space around the + combinator is optional but recommended. */
former_element + target_element { style properties }
示例
基本用法
此示例演示如何选择特定类型的下一个兄弟元素。
CSS
我们只为紧跟在其类型中第一个 <li> 之后的 <li> 设置样式
css
li:first-of-type + li {
color: red;
font-weight: bold;
}
HTML
html
<ul>
<li>One</li>
<li>Two!</li>
<li>Three</li>
</ul>
结果
选择上一个兄弟元素
相邻兄弟组合器可以包含在 :has() 函数式选择器中,以选择上一个兄弟元素。
CSS
我们只为具有下一个兄弟元素(即其类型中最后一个 <li>)的 <li> 设置样式
css
li:has(+ li:last-of-type) {
color: red;
font-weight: bold;
}
HTML
html
<ul>
<li>One</li>
<li>Two</li>
<li>Three!</li>
<li>Four</li>
</ul>
结果
规范
| 规范 |
|---|
| 选择器 Level 4 # 相邻兄弟组合器 |
浏览器兼容性
加载中…