Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 203
user934902 Avatar asked Oct 11 '13 17:10

user934902


People also ask

How do you target your first and second child in CSS?

The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.

How do I choose a multiple nth child?

Definition and UsageThe :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.


1 Answers

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/

like image 199
412 Avatar answered Sep 21 '22 21:09

412