BarryBones41 BarryBones41 - 3 months ago 5
CSS Question

Select nth-child of high level selector

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>')
}


JSFiddle

Answer

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

JSFiddle