>
是child combinator,有时被错误地称为直系后代组合1
这意味着 Select 器div > p.some_class
只匹配嵌套在directly inside和div
中的.some_class
的段落,而不匹配嵌套在其中的任何段落.这意味着匹配div > p.some_class
的每个元素必然也匹配div p.some_class
,与descendant combinator(空格)匹配,所以这两个元素经常混淆是可以理解的.
比较子组合子与子组合子的图示:
div > p.some_class {
background: yellow;
}
div p.some_class {
color: red;
}
<div>
<p class="some_class">Some text here</p> <!-- [1] div > p.some_class, div p.some_class -->
<blockquote>
<p class="some_class">More text here</p> <!-- [2] div p.some_class -->
</blockquote>
</div>
哪些元素与哪些 Select 器匹配?
Matched by both div > p.some_class
and div p.some_class
This p.some_class
is located directly inside the div
, hence a parent-child relationship is established between both elements. Since "child" is a type of "descendant", any child element is by definition also a descendant. Therefore, both rules are applied.
Matched by only div p.some_class
This p.some_class
is contained by a blockquote
within the div
, rather than the div
itself. Although this p.some_class
is a descendant of the div
, it's not a child; it's a grandchild. Therefore, only the rule with the descendant combinator in its selector is applied.
1 Many people go further to call it "direct child" or "immediate child", but that's completely unnecessary (and incredibly annoying to me), because a child element is immediate by definition anyway, so they mean the exact same thing. There's no such thing as an "indirect child".