子组合器

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
# 子代选择器

浏览器兼容性

另见