2010-07-12 123 views

回答

560

>child combinator,有时错误地称为直接后代组合子。

这意味着选择div > p.some_class仅选择的.some_class段落,它们嵌套直接内部一个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> 

什么是选择,什么是不:

  1. 选择
    p.some_class直接位于div内,因此父子关系之间建立这两个要素。

  2. 没有选择
    p.some_class由包含在div内,而不是div本身。虽然这p.some_classdiv的后裔,但它不是一个孩子;这是一个孙子。

    因此,虽然div > p.some_class将不匹配此元素,div p.some_class将使用descendant combinator来代替。


很多人去进一步称之为“直子”或“直接子”,但这是完全没有必要的(和令人难以置信的讨厌我),因为一个子元素是立竿见影无论如何,的定义是,所以它们的意思完全相同。没有“间接孩子”这样的事情。

+2

+1它真的叫做*孩子选择器*吗?如果是这样,那就很容易让人误解。我会想'#something a'会是一个孩子选择器。 – alex 2010-09-08 01:31:02

+2

@alex:[是](http://www.w3.org/TR/CSS2/selector.html#child-selectors):)'#something a''可能意味着'a'是一个孙子或伟大的孙子孙子'#something'(它没有考虑到嵌套深度)。 – BoltClock 2010-09-08 01:33:06

+0

嗯,我的意思是,它仍然是一个孩子......一个孙子也许:P – alex 2010-09-08 01:45:46

2

全部p标签含类别some_class这是div标签的直接子代。

+0

不是孩子,直接孩子 – Imad 2016-09-16 06:52:17

6

它与p元素some_class直接根据div

9

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

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

+0

非常感谢您的链接!那里我也发现了“相邻兄弟选择器”。 – 2010-07-12 04:46:57

+0

您将在Sitepoint上找到[浏览器支持](http://reference.sitepoint.com/css/childselector#compatibilitysection)。在IE6中不起作用,如果它对你的项目很重要,可以在其他地方使用。这个资源是特别的。有用的兄弟姐妹,:nth-​​child()等支持仍然不完整 – FelipeAls 2010-07-12 04:59:06

1
HTML
<div> 
    <p class="some_class">lohrem text (it will be of red color)</p>  
    <div> 
     <p class="some_class">lohrem text (it will NOT be of red color)</p> 
    </div> 
    <p class="some_class">lohrem text (it will be of red color)</p> 
</div> 
CSS
div > p.some_class{ 
    color:red; 
} 

所有的直接孩子是<p>.some_class会得到应用到他们的风格。

0

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

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

有关CSS策[讲师和他们使用的更多信息,请查看我的博客, css selectorscss3 selectors

7

>(大于号)是一个CSS Combinator的。

组合器是解释选择器之间关系的东西。

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

有在CSS3四个不同的组合子:

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

注意:<在CSS中无效选择。

enter image description here

例如:

<!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> 

输出:

enter image description here

More information about CSS Combinators