semsem semsem - 19 days ago 5
CSS Question

nth-child based in element index

I want to use css3 nth-child to select matched elements based in their index in the whole document (like jquery :eq() selector) not based in the parent element.

<div id="container">
<div class="result">
<div class="active">content 1</div>
</div>

<div class="result">
<div class="active">content 2</div>
</div>

<div class="result">
<div class="active">content 2</div>
</div>
</div>


This css code select all elements because every .active is 1st child respective to the parent .result

.active:nth-child(1) {
background: red;
}


I tried also to make the body as parent

body > .active:nth-child(1) {
background: red;
}


But it can't do the job.

I want nth-child(1) selects content 1
and nth-child(2) selects content 2

Answer

I think you want to use nth-child on .result.

#container .result:nth-child(1) .active {
  background: red;
}

JSBin