子組合器

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

子代選擇器 (>) 放置在兩個 CSS 選擇器之間。它只匹配那些作為第一個選擇器匹配的元素的直接子代的第二個選擇器匹配的元素。

css
/* List items that are children of the "my-things" list */
ul.my-things > li {
  margin: 2em;
}

第二個選擇器匹配的元素必須是第一個選擇器匹配的元素的直接子代。這比後代選擇器更嚴格,後者匹配所有第二個選擇器匹配的元素,只要存在一個與第一個選擇器匹配的祖先元素,無論在 DOM 中向上有多少“跳”。

語法

css
/* The white space around the > combinator is optional but recommended. */
selector1 > selector2 { /* style properties */ }

示例

CSS

css
span {
  background-color: aqua;
}

div > span {
  background-color: yellow;
}

HTML

html
<div>
  <span>
    Span #1, in the div.
    <span>Span #2, in the span that's in the div.</span>
  </span>
</div>
<span>Span #3, not in the div at all.</span>

結果

規範

規範
選擇器 Level 4
# 子代選擇器

瀏覽器相容性

另見