2014-02-18 22 views
1

我想要一个div的背景颜色替代。红色,黑色,红色,黑色......这时候的元素都在同一层级工作正常,但我不能让它在这种情况下工作:nth类型的CSS选择器层次问题

<div class="post-preview-wrapper"> 
    <div class="post-preview"> 
     <h1>Lorem ipsum dolor sit amet.</h1> 
    </div> 
</div> 
<div class="post-preview-wrapper"> 
    <div class="post-preview"> 
     <h1>Adipisicing elit. A cumque!Lorem ipsum dolor sit amet.</h1> 
    </div> 
</div> 

而CSS

.post-preview:nth-of-type(even) { 
    background-color: red; 
} 

.post-preview:nth-of-type(odd) { 
    background-color: black; 
} 

任何提示如何正确设置选择器?非常感谢!

回答

3

http://jsfiddle.net/L6nwC/

您可能需要运行在容器上的第n个孩子......

.post-preview-wrapper:nth-of-type(even) .post-preview{ 
    background-color: red; 
} 

.post-preview-wrapper:nth-of-type(odd) .post-preview { 
    background-color: black; 
    color: white; 
} 
+0

谢谢,这很好! – psteinweber

+1

男人,你是一个拯救生命的人! –

0

Fiddle Demo

.post-preview-wrapper:nth-of-type(even) { 
    background-color: red; 
} 

.post-preview-wrapper:nth-of-type(odd) { 
    background-color: black; 
} 
+0

感谢,可惜的是应用背景的父母在我的CAS不工作即 – psteinweber

1

nth-of-type

Live Demo

.post-preview-wrapper:nth-of-type(even) .post-preview{ 
    background-color: red; 
} 

.post-preview-wrapper:nth-of-type(odd) .post-preview{ 
    background-color: black; 
} 

nth-child也适用

Live Demo

.post-preview-wrapper:nth-child(2n) .post-preview{ /* even*/ 
    background-color: red; 
} 

.post-preview-wrapper:nth-child(2n+1) .post-preview{ /* odd */ 
    background-color: black; 
} 
+0

谢谢,这工作正常。我接受了第一个回答这个解决方案的建议。 – psteinweber