Reputation: 1481
How do I use the pseudo-class nth-child
of a selector that is not the immediate parent of said child?
HTML
<div id="main">
</div>
CSS
.test {
width: 100px;
height: 100px;
background: red;
}
#main .test:nth-child(even) {
background: green;
}
JS
// doesnt work
for (var i = 0; i < 3; i++) {
$('#main').append('<div><div class="test"></div></div>')
}
// works
for (var i = 0; i < 3; i++) {
$('#main').append('<div class="test"></div>')
}
Upvotes: 2
Views: 124
Reputation: 171
As you have two different kind of structures in your html, use different selectors for styling
#main .test:nth-child(even) ,
#main div:nth-child(even) > .test{
background: green;
}
https://jsfiddle.net/9yq0bhjk/4/
Upvotes: 1
Reputation: 6894
If you want to select the .test
div, you need to select every even child of #main
, then select the .test
within.
CSS
#main div:nth-child(even) .test {
background: green;
}
Upvotes: 3