How to choose second and third element (li) in <ul> tag (with CSS)?

16,916

Solution 1

Chain two :nth-child() pseudoclasses to match a range of adjacent elements:

li:nth-child(n+2):nth-child(-n+3) {
  margin-right: 50px;
}

this will select both the second and the third li acting like the logical and operator.

Codepen Demo


Visual result of the effect of these psuedoclasses chained:

enter image description here

Solution 2

For second child you can use

li:nth-child(2){}

and for third child use

li:nth-child(3){}

Solution 3

CSS has a :nth-child selector just for that. You can do something like this :

ul > li:nth-child(3){ ... }

Read more about this at here

Solution 4

All the answers are correct. Summed up, your code would look like:

ul > li:first-child {
    margin-right: 50px;
}

ul > li:nth-child(2) {
    margin-right: 50px;
}

ul > li:nth-child(3) {
    margin-right: 50px;
}
Share:
16,916
Nedim
Author by

Nedim

Front-End Developer / Digital Marketing

Updated on June 05, 2022

Comments

  • Nedim
    Nedim almost 2 years

    I have this code to select my first, second and third li tag, but i was asking myself if it was possible to write this code shorter. I usually don't use the child() selector so I don't know much about it.

    ul > :first-child{
        margin-right: 50px;
    }
    
    ul > :first-child + li{
        margin-right: 50px;
    }
    
    ul > :first-child + li + li{
        margin-right: 50px;
    }