Css is odd, not even working with pseudo elements
I have container div names wrapper
and it has multiple child divs named thumb
I want to apply css pseudo elements
to even and odd.
My codes
<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>
And my css:
.wrapper:nth-child(even) .thumb:after{
//some codes
}
.wrapper:nth-child(odd) .thumb:after{
//some codes
}
But I only get styles odd
.
Since the odd
and even relationship is applied based on the sibling index, you need to apply it on col-half
as it is a repeating item.
Since your element thumb
is the first child of its parent, it will only satisfy the selectorodd
.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>
You have a misunderstanding of: nth-child as it does not work as "the nth child of this container", but as "I am 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 of this selector has indeed caused a lot of confusion as it is too easy to misunderstand how you did it.
.col-half:nth-child(even) {
color: green;
}
.col-half:nth-child(odd) {
color: red;
}
Try it like this: Demo
In your css, you are using a parent div to display even and odd. Instead, you need to use odd / even for children that repeat
.col-half:nth-child(even) .thumb{
background:#ccc;
}
.col-half:nth-child(odd) .thumb{
background:#f00;
}
Try this
.wrapper .col-half:nth-child(2n) .thumb:after {
content: '';
}
.wrapper .col-half:nth-child(2n-1) .thumb:after {
content: '';
}