user934902
user934902

Reputation: 1204

Targeting first 2 children or last 2 children

I know a bunch of the pseudo classes (first-child, last-child, nth-child) but I am having trouble selecting the first 2 children in a list or the last 2, the list is dynamic and changes all the time so i cant target based on counting the li's

<ul>
 <li></li>
 <li></li>
 <li></li>
 <li></li>
 <li></li>
 <li></li>
</ul>

Upvotes: 34

Views: 40042

Answers (1)

412
412

Reputation: 1428

For the first two children you can use:

ul li:nth-child(-n + 2) {
    color: orange;
}

http://jsfiddle.net/nYnSz/1/

For the last two:

ul li:nth-last-child(-n + 2) {
    color: orange;
}

http://jsfiddle.net/nYnSz/

Upvotes: 75

Related Questions