“>"是什么意思?(大于号) CSS 选择器是什么意思? [英] What does the ">" (greater-than sign) CSS selector mean?

查看:39
本文介绍了“>"是什么意思?(大于号) CSS 选择器是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

div > p.some_class {
  /* Some declarations */
}

> 符号到底是什么意思?

What exactly does the > sign mean?

推荐答案

>子组合器,有时被错误地称为直接后代组合器.1

> is the child combinator, sometimes mistakenly called the direct descendant combinator.1

表示选择器 div >p.some_class 仅匹配 .some_class 中嵌套直接在 div 内的段落,而不匹配任何进一步嵌套的段落在里面.这意味着每个元素匹配 div >p.some_class 也必然与 div p.some_class 匹配,带有 后代组合子(空格),所以这两者经常混淆是可以理解的.

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?

  1. 由两个 div > 匹配p.some_classdiv p.some_class
    这个 p.some_class 直接位于 div 内部,因此在两个元素之间建立了父子关系.自从孩子"是一种后代",任何子元素根据定义也是后代.因此,两个规则都适用.

  1. 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.

仅由 div p.some_class
匹配此 p.some_class 包含在 div 内的 blockquote 中,而不是 div 本身.虽然这个 p.some_classdiv 的后代,但它不是一个孩子;这是一个孙子.因此,仅应用在其选择器中具有后代组合器的规则.

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 很多人更进一步称其为直子";或直接子元素",但这完全没有必要(而且对我来说非常烦人),因为子元素无论如何都是直接的定义,所以它们的含义完全相同.没有所谓的间接孩子".

这篇关于“&gt;"是什么意思?(大于号) CSS 选择器是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆