I want to apply CSS background color to nth child 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 any simpler way in CSS?
.roundperiodbg:nth-child(3), .roundperiodbg:nth-child(4), ..... .roundperiodbg:nth-child(10) {
background : green;
}
You can use two :nth-child()
selectors to create a range like this:
.roundperiodbg:nth-child(n+3):nth-child(-n+10){
background : green;
}
See this demo fiddle.
:nth-child(n+3)
selects all elements with an index equal or great than 3
------
n | i
------
0 | 3
------
1 | 4
------
2 | 5
------
3 | 6
------
..| ..
:nth-child(-n+10)
selects all elements with an index equal or lower than 10
------
n | i
------
0 | 10
------
1 | 9
------
2 | 8
------
3 | 7
------
..| 1
When you apply both in the same CSS rule the element would have to match both conditions therefore it only applies to elements with index between 3 and 10.
Also you can check out this link for more cool uses of the :nth-child()
selector. Thanks @Rajaprabhu
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