Reputation: 714
I have a container div names wrapper
and it has several child divs named thumb
I want to apply css pseudo elements
with the even and odd.
<div class="wrapper">
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
</div>
.wrapper:nth-child(even) .thumb:after{
//some codes
}
.wrapper:nth-child(odd) .thumb:after{
//some codes
}
But i am getting only odd
styles.
Upvotes: 4
Views: 998
Reputation: 536
Try This One
.wrapper .col-half:nth-child(2n) .thumb:after {
content: '';
}
.wrapper .col-half:nth-child(2n-1) .thumb:after {
content: '';
}
Upvotes: 0
Reputation: 7207
Try like this: Demo
In your css, You are using the parent div for showing even and odd. Instead you need to use odd / even for child elements which repeats
.col-half:nth-child(even) .thumb{
background:#ccc;
}
.col-half:nth-child(odd) .thumb{
background:#f00;
}
Upvotes: 0
Reputation: 56754
You have a misunderstanding about :nth-child as it does not work as "nth child of this container" but as "am I the nth child of my parent?".
So you need to apply :nth-child(odd/even)
to .col-half
:
.col-half:nth-child(even) .thumb:after{
//some codes
}
.col-half:nth-child(odd) .thumb:after{
//some codes
}
The name for this selector has really caused many misunderstandings as it is too easy to misunderstand the way you did.
Upvotes: 1
Reputation: 388316
Since the odd
and even relationship is applied based on sibling index, you need to apply it on col-half
as that is the repeated element.
Since your thumb
element is the first child of its parent, it will only satisfy the odd
selector
.wrapper .col-half:nth-child(even) .thumb:after {
content: 'x'
}
.wrapper .col-half:nth-child(odd) .thumb:after {
content: 'y'
}
<div class="wrapper">
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
<div class="col-half">
<div class="thumb">
...
</div>
</div>
</div>
Upvotes: 4
Reputation: 87203
.col-half:nth-child(even) {
color: green;
}
.col-half:nth-child(odd) {
color: red;
}
Upvotes: 0