Manik Manik - 1 month ago 7
CSS Question

nth child selctor css

i have a div pattern here , this pattern have minimum 9 number of and this pattern is repeating . The background color of div is given

1 white
2 green
3 white
4 green
5 white
6 green
7 green
8 white
9 green


so to make it work i write following css

$(".test:nth-child(odd)").css("background-color","green");
$(".test:nth-child(even)").css("background-color","green");
$(".test:nth-child(7n)").css("background-color","green");
$(".test:nth-child(8n)").css("background-color","white");
$(".test:nth-child(9n)").css("background-color","green");


Now everything work , but the problem is that when number of divs comes more than 9 then the 10th div is starting from background green but it need to be white .

for example if there is 18 div then

1 white
2 green
3 white
4 green
5 white
6 green
7 green
8 white
9 green
10 white
11 green
12 white
13 green
14 white
15 green
16 green
17 white
18 green


please suggest good formula to solve this

Answer

Correct me if I'm wrong but I think you want to inverse pattern after 7 (which should be white but you want it green)

.test {
  padding: 5px;
  border: 1px solid black;
  margin: 5px;
  display: inline-block;
}

/* Every other child starting at 1 */
.test:nth-child(2n + 1) {
  background-color: white;
}

/* Every other child starting at 2 */
.test:nth-child(2n + 2) {
  background-color: green;
}

/* Every other child starting at 7 */
.test:nth-child(2n + 7) {
  background-color: green;
}

/* Every other child starting at 8 */
.test:nth-child(2n + 8) {
  background-color: white;
}

/* Every other child starting at 16 */
.test:nth-child(2n + 16) {
  background-color: green;
}

/* Every other child starting at 17 */
.test:nth-child(2n + 17) {
  background-color: white;
}
<div class="test">1 white</div>
<div class="test">2 green</div>
<div class="test">3 white</div>
<div class="test">4 green</div>
<div class="test">5 white</div>
<div class="test">6 green</div>
<div class="test">7 green</div>
<div class="test">8 white</div>
<div class="test">9 green</div>
<div class="test">10 white</div>
<div class="test">11 green</div>
<div class="test">12 white</div>
<div class="test">13 green</div>
<div class="test">14 white</div>
<div class="test">15 green</div>
<div class="test">16 green</div>
<div class="test">17 white</div>
<div class="test">18 green</div>

I've commented the code to make it easier to understand

I've used CSS but you can set this with Jquery if you like (as you are currently)

Hope this helps.