Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth child without duplication in css [duplicate]

Tags:

html

css

sass

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 ?

like image 993
Giala Jefferson Avatar asked Apr 20 '17 05:04

Giala Jefferson


Video Answer


2 Answers

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>
like image 177
Pranav C Balan Avatar answered Oct 19 '22 09:10

Pranav C Balan


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>
like image 1
Harikrishnan N Avatar answered Oct 19 '22 08:10

Harikrishnan N