Easiest way to apply CSS background color for n-th child from 3 to 10

I want to apply CSS background color to nth child from 3 to 10

    <div class="roundperiodbg" id="roundPeriod1" title="PERIOD 1"></div>
    <div class="roundperiodbg" id="roundPeriod2" title="PERIOD 1"></div>

    <div class="roundperiodbg" id="roundPeriod3" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod4" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod5" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod6" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod7" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod8" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod9" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod10" title="PERIOD 2"></div>

    <div class="roundperiodbg" id="roundPeriod11" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod12" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod13" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod14" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod15" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod16" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod17" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod18" title="PERIOD 3"></div>

This works, but is there an easier way in CSS?

.roundperiodbg:nth-child(3), .roundperiodbg:nth-child(4), ..... .roundperiodbg:nth-child(10) {
        background : green;

}
+4
source share
5 answers

You can use two selectors :nth-child()to create such a range:

.roundperiodbg:nth-child(n+3):nth-child(-n+10){
     background : green;
}

See this demo script .

Explanation:

:nth-child(n+3) selects all items with an index equal to or greater than 3

------
n | i
------
0 | 3
------
1 | 4
------
2 | 5
------
3 | 6
------
..| ..

:nth-child(-n+10) selects all items with an index equal to or lower than 10

------
n | i
------
0 | 10
------
1 | 9
------
2 | 8
------
3 | 7
------
..| 1

When you apply both rules in the same CSS, the element must meet both conditions, so it applies only to elements with an index of 3 to 10.


:nth-child(). @Rajaprabhu

+14

, :

.roundperiodbg-green {
   background: green;
}

div, ?

0

Create a container, put all your items in a container. and use below css code:

.container>div:nth-child(n+3){
  background : green;
}

Look at this script

0
source

Try

    .roundperiodbg{ background:#333; height:10px; width:100%; margin:5px;}
    .roundperiodbg:nth-child(n + 4){ background:green;}
0
source

You can use the following code -

$('.roundperiodbg:gt(2):lt(10)').css('background','green');

This :gt(n)indicates that any item will be selected after the nth item, and lt(n)sets any item before the nth item is selected

-1
source

Source: https://habr.com/ru/post/1546786/


All Articles