11
div div p:nth-child(1 to 5)

How can I select multiple numbers with the nth-child, so I get the child elements 1 to 5 without having to write:

div div p:nth-child(1),
div div p:nth-child(2),
div div p:nth-child(3),
div div p:nth-child(4),
div div p:nth-child(5) {

}

So it should look like this:

div div p:nth-child(1 to 5)
2
  • You can use a CSS pre-processer like SASS or LESS - but it'll only compile to the exact same thing you have written. Interesting question - why is having this on one line important to you? What do you win for putting it on one line? Commented Apr 21, 2014 at 18:51
  • A lot of useful nth-child tricks are summarised by css-tricks.
    – m7913d
    Commented May 31, 2020 at 15:10

4 Answers 4

11
div div p:nth-child(n+1):nth-child(-n+5){

}

will select elements 1 to 5

9
div div p:nth-child(-n+5){

}

This will select the first 5 children.

2
5

I've attached a link to a JSFiddle that should do what you are asking, but it should look something like this:

li:nth-child(-n+5){
    color: red;
}

http://jsfiddle.net/p2aBc/1/

1
  • 1
    you can click 'set as base' in jsfiddle so u wont need to change your link :P
    – Banana
    Commented Apr 21, 2014 at 18:56
5
div div p:nth-child(1),
div div p:nth-child(2),
div div p:nth-child(3),
div div p:nth-child(4),
div div p:nth-child(5){

}

Or

div div p:nth-child(-n+5){

}
1
  • Sorry wrong question how can I make this to just one line? and not: Commented Apr 21, 2014 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.