2010-07-12 120 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