Reputation: 813
I want the background color of a div to alternative. Red, black, red, black... It works fine when the elements are in the same hierarchy level, but I can't get it working in this case:
<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>
And the CSS
.post-preview:nth-of-type(even) {
background-color: red;
}
.post-preview:nth-of-type(odd) {
background-color: black;
}
Any hints how to set up the selector properly? Thanks a lot!
Upvotes: 1
Views: 298
Reputation: 16472
.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 also works
.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;
}
Upvotes: 1
Reputation: 22547
You might want to run the nth-child on the container...
.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;
}
Upvotes: 3
Reputation: 3964
.post-preview-wrapper:nth-of-type(even) {
background-color: red;
}
.post-preview-wrapper:nth-of-type(odd) {
background-color: black;
}
Upvotes: 0