“>"是什么意思?(大于号)CSS 选择器是什么意思? [英] What does the ">" (greater-than sign) CSS selector mean?
问题描述
例如:
div >p.some_class {/* 一些声明 */}
>
符号到底是什么意思?
>
是 子组合子,有时被误称为直接后代组合子.1
这意味着选择器 div >p.some_class
只匹配 .some_class
的直接嵌套在一个 div
内的段落,而不匹配任何进一步嵌套的段落之内.这意味着每个元素匹配 div >p.some_class
也必须匹配 div p.some_class
,带有 后代组合符(空格),所以这两者经常被混淆是可以理解的.
比较子组合器和后代组合器的插图:
div >p.some_class {背景:黄色;}div p.some_class {红色;}
<p class="some_class">这里有一些文字</p><!-- [1] div >p.some_class, div p.some_class --><blockquote><p class="some_class">更多文字在这里</p><!-- [2] div p.some_class --></blockquote>
哪些元素被哪些选择器匹配?
由
div > 匹配p.some_class
和div p.some_class
这个p.some_class
直接位于div
内部,因此在两个元素之间建立了父子关系.自从孩子"是后代"的类型,任何子元素根据定义也是后代.因此,这两条规则都适用.仅匹配
div p.some_class
这个p.some_class
包含在div
中的blockquote
中,而不是div
本身.虽然这个p.some_class
是div
的后代,但它不是一个孩子;这是一个孙子.因此,仅应用其选择器中带有后代组合器的规则.
1 许多人更进一步称其为直系子";或直接子元素",但这完全没有必要(而且对我来说非常烦人),因为子元素无论如何都是直接的定义,所以它们的意思完全相同.没有间接孩子"这样的东西.
For example:
div > p.some_class {
/* Some declarations */
}
What exactly does the >
sign mean?
>
is the child combinator, sometimes mistakenly called the direct descendant combinator.1
That means the selector div > p.some_class
only matches paragraphs of .some_class
that are nested directly inside a div
, and not any paragraphs that are nested further within. This implies that every element matching div > p.some_class
necessarily also matches div p.some_class
, with the descendant combinator (space), so the two are understandably often confused.
An illustration comparing the child combinator with the 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>
Which elements are matched by which selectors?
Matched by both
div > p.some_class
anddiv p.some_class
Thisp.some_class
is located directly inside thediv
, 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
Thisp.some_class
is contained by ablockquote
within thediv
, rather than thediv
itself. Although thisp.some_class
is a descendant of thediv
, 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".
这篇关于“>"是什么意思?(大于号)CSS 选择器是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!