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.
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>
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.
.col-half:nth-child(even) {
color: green;
}
.col-half:nth-child(odd) {
color: red;
}
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;
}
Try This One
.wrapper .col-half:nth-child(2n) .thumb:after {
content: '';
}
.wrapper .col-half:nth-child(2n-1) .thumb:after {
content: '';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.