我希望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;
}
任何提示如何正确设置选择器?非常感谢!
答案 0 :(得分:3)
您可能希望在容器上运行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)
.post-preview-wrapper:nth-of-type(even) {
background-color: red;
}
.post-preview-wrapper:nth-of-type(odd) {
background-color: black;
}