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

4

5

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;
}
Merodach answered 7/4, 2016 at 12:7 Comment(0)
B
12

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

Bookrack answered 7/4, 2016 at 12:9 Comment(5)
Thank you, but i don't understand "(n+2)" and "(-n+3)". What if i want to select my first, second and third li tag and not the fourth?Merodach
the draw I just posted might give you an hint. If not, just change n+2 with n+1 (or simply omit the first pseudoclass). in this example 2 and 3 are respectively the lower and the upper boundBookrack
Why do not you only use nth-child(1), nth-child(2) etc.?Parlor
Because if you need to select a larger range of elements (e.g 1-4) that way would result in a longer declaration.Bookrack
I've bene using nth-of-type for years (and nth-child) and had no idea you could use it twice to get an intersection. Also: great artwork :)Fascism
I
5

For second child you can use

li:nth-child(2){}

and for third child use

li:nth-child(3){}
Iodism answered 7/4, 2016 at 12:14 Comment(1)
This is easy to use, but it's just copy paste work so i prefer to use something shorter :) Thank you anywayMerodach
S
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

Saltatorial answered 7/4, 2016 at 12:10 Comment(1)
Thank you, and how can I for example select the first, second and third li tag at the same time?Merodach
A
1

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;
}
Allegorist answered 7/4, 2016 at 12:42 Comment(2)
This works pretty well, but i found something shorter than this :D Thanks to @fcalderan i have this code: ` li:nth-child(n+1):nth-child(-n+3) { margin-right: 50px; } `Merodach
Does this only affect the first three elements, or will it also affect i.e. the sixth element? @NedimKurtAllegorist

© 2022 - 2024 — McMap. All rights reserved.