I want to style item 1 to 10 but rather than do
&.nth-child(1) { //style }
&.nth-child(2) { //style }
&.nth-child(3) { //style }
and so on..
any range selector in css ?
You can use :nth-child
with equation in an+b
format(where replace a
and b
with an integer and n
would be 0, 1, 2,....
).
li:nth-child(-n+10) {
color: red
}
<ol>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
</ol>
UPDATE : If you need elements within a range then use multiple :nth-child
selector.
li:nth-child(n+5):nth-child(-n+10) {
color: red
}
<ol>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
</ol>
The below snippet applies css to range from 2 to 3. Tweak it to your requirement.
Explanation:
nth-child(n+2)
starts selecting from 2nd element to forward.
nth-child(-n+3)
starts selecting from 3rd element to backwards.
Combining two results in range.
li:nth-child(n+2):nth-child(-n+3){
background: #000;
color: #fff
}
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With