相鄰兄弟組合器
相鄰兄弟組合器 (+) 分隔兩個選擇器,僅當第二個元素緊跟在第一個元素之後,並且兩者都是同一父 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 # 相鄰兄弟組合器 |
瀏覽器相容性
載入中…