nth-of-type CSS选择器层次结构问题

时间:2014-02-18 04:48:19

标签: css css-selectors

我希望div的背景颜色可供选择。红色,黑色,红色,黑色......当元素处于相同的层次结构级别时它工作正常,但在这种情况下我无法使其工作:

<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 个答案:

答案 0 :(得分:3)

http://jsfiddle.net/L6nwC/

您可能希望在容器上运行nth-child ...

.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;
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

Fiddle Demo

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

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