2011-03-04 105 views
11

我有一個網站是這樣的:問題,在第n個孩子奇/偶子元素

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 
    <link rel="stylesheet" type="text/css" href="article_style.css" /> 
</head> 
<body> 
    <div class="section"> 
    <!--<h1>header</h1>--> 
     <div> 
      paragraph 
     </div> 
     <div> 
      paragraph 
     </div> 
     <div> 
      paragraph 
     </div> 
    </div> 
    <div class="section"> 
     <div> 
      paragraph 
     </div> 
     <div> 
      paragraph 
     </div> 
     <div> 
      paragraph 
     </div> 
    </div> 
</body> 
</html> 

,這是CSS:

div.section 
{ 
    border: 1px solid black; 
} 
div.section div:nth-child(even) 
{ 
    color: Green; 
} 
div.section div:nth-child(odd) 
{ 
    color: Red; 
} 

這是結果:

result

這是好的,因爲我得到紅色的奇數和綠色甚至在每個部分。 但是,當我在首節begginig添加標題(註釋示例代碼中)我得到這樣的:

result2

,我不希望出現這種情況。我想要像以前一樣,但只是在第一部分有一個標題。所以首先標題然後是紅色段落。

回答

48

使用nth-of-type代替:

Live Demo

div.section 
{ 
    border: 1px solid black; 
} 
div.section div:nth-of-type(even) 
{ 
    color: Green; 
} 
div.section div:nth-of-type(odd) 
{ 
    color: Red; 
} 
+0

謝謝,它的工作原理! 但是,我不確定爲什麼任何人都會使用'nnth-child',如果它不看類型。它有什麼用處? – 2011-03-04 15:22:06

+0

@ CichyK24:經典的用例是[斑馬條紋](http://dev.opera.com/articles/view/zebra-striping-tables-with-css3/)表或列的行。 – thirtydot 2011-03-04 15:23:51

+0

是的,但是它也不能用於「nth-type-type」嗎? – 2011-03-04 15:40:29

4
div > :nth-child(3)  the third child of a div element 
div > :nth-child(even) every even child of a div element 
div > :nth-child(odd) every odd child of a div element 
div > :nth-child(3n) every third child of a div element