BarryBones41
BarryBones41

Reputation: 1481

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

Upvotes: 2

Views: 124

Answers (2)

Murtoza
Murtoza

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

Hunter Turner
Hunter Turner

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

JSFiddle

Upvotes: 3

Related Questions