CSS选择器的">"(大于号)是什么意思?

Mis*_*hko 456 css css-selectors

例如:

div > p.some_class {
  /* Some declarations */
}
Run Code Online (Sandbox Code Playgroud)

这个>符号究竟意味着什么?

Bol*_*ock 648

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

这意味着选择器div > p.some_class只选择直接.some_class嵌套 a中的div段落,而不是任何嵌套在其中的段落.

举例说明:

<div>
    <p class="some_class">Some text here</p>     <!-- Selected [1] -->
    <blockquote>
        <p class="some_class">More text here</p> <!-- Not selected [2] -->
    </blockquote>
</div>
Run Code Online (Sandbox Code Playgroud)

选择了什么,什么不是:

  1. 选择
    p.some_class直接位于其中div,因此在两个元素之间建立父子关系.

  2. 未选中
    p.some_class包含在blockquote内部div,而不是内部div.虽然这p.some_class是后代div,但它不是孩子; 这是一个孙子.

    因此,虽然div > p.some_class不会匹配此元素,但div p.some_class将使用后代组合器.


1 许多人进一步将其称为"直接孩子"或"直接孩子",但这完全没有必要(并且令我非常讨厌),因为无论如何,子元素无论如何都是立即,因此它们意味着完全相同的事情.没有"间接的孩子"这样的东西.

  • 当有人是他们的祖父母的孩子时,我们正在处理一个非常令人讨厌的乱伦事件.令人高兴的是,这在HTML中是不可能的. (31认同)
  • @alex它被称为[儿童组合者](http://www.w3.org/TR/css3-selectors/#child-combinators),这个空间被称为[后代组合者](http://www.w3.组织/ TR/CSS3选择器/#后裔,组合子) (11认同)
  • 为了清楚起见,我没有听到任何外行人称他们的孩子为直系孩子. (8认同)
  • +1它真的被称为*子选择器*吗?如果是这样,这是非常误导的.我认为`#something a`将是一个儿童选择器. (2认同)
  • @alex:[是](http://www.w3.org/TR/CSS2/selector.html#child-selectors):)`#something a`可能意味着'a`是孙子或者伟大的孙子`#thing`(它没有考虑嵌套的深度). (2认同)
  • 我错过了什么吗?孩子会是下一个级别。后代可以是任意数量的低级。所以在这种情况下,孩子==直系后代。那么为什么它“有时被错误地称为直接后代组合器”呢?直系孩子是错误的,但直系后代似乎是正确的?如果我在这里错了,请纠正我。 (2认同)

Pre*_*raj 35

> (大于号)是一个CSS组合器.

组合器可以解释选择器之间的关系.

CSS选择器可以包含多个简单选择器.在简单的选择器之间,我们可以包括组合器.

CSS3中有四种不同的组合器:

  1. 后代选择器(空间)
  2. 子选择器(>)
  3. 相邻的兄弟选择器(+)
  4. 一般兄弟选择器(〜)

注意: <在CSS选择器中无效.

在此输入图像描述

例如:

<!DOCTYPE html>
<html>
<head>
<style>
div > p {
    background-color: yellow;
}
</style>
</head>
<body>

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <span><p>Paragraph 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

有关CSS组合器的更多信息


Dag*_*bit 11

正如其他人所说,它是一个儿童选择器.这是适当的链接.

http://www.w3.org/TR/CSS2/selector.html#child-selectors


dan*_*n04 7

它匹配p与类元素some_class直接div.


tsc*_*ble 5

p具有类的所有标签some_class都是标签的直接子代div


Avi*_*tra 5

(子选择器)是在 css2 中引入的。div p{ } 选择 div 元素的所有 p 元素,而 div > p 只选择子 p 元素,而不是孙子、曾孙子等等。

<style>
  div p{  color:red  }       /* match both p*/
  div > p{  color:blue  }    /* match only first p*/

</style>

<div>
   <p>para tag, child and decedent of p.</p>
   <ul>
       <li>
            <p>para inside list. </p>
       </li>
   </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

有关 CSS Ce[lectors 及其使用的更多信息,请查看我的博客、 css 选择器css3 选择器