psteinweber
psteinweber

Reputation: 813

nth-of-type CSS selector hierarchy issues

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

Answers (3)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

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 also works

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

Upvotes: 1

superUntitled
superUntitled

Reputation: 22547

http://jsfiddle.net/L6nwC/

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

Karuppiah RK
Karuppiah RK

Reputation: 3964

Fiddle Demo

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

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

Upvotes: 0

Related Questions