Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-child() or first-child? how to select first AND second child in one

I'd like to select the first two list items in an unordered list. I can select the first item thus:

ul li:nth-child(1) a {     background: none repeat scroll 0 0 beige; } 

OR

ul li:first-child a {     background: none repeat scroll 0 0 beige; } 

I'd like to select both the first and second line item - how do I do that?

like image 718
Doug Fir Avatar asked Jan 11 '12 14:01

Doug Fir


People also ask

How do I select 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 Nth children choose multiple children?

The :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.

How do you select the first two elements in CSS?

The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+2) will select the first 2 li elements.

How do I select a specific sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".


1 Answers

For selecting the first and second children, you can use a single :nth-child() pseudo-class like so:

ul li:nth-child(-n+2) a {     background: none repeat scroll 0 0 beige; } 
like image 200
BoltClock Avatar answered Sep 29 '22 08:09

BoltClock