Quick problem with nth-child

I have a quick :nth-child question that I am trying to solve. I aim to target every third and fourth items in a group of 4 items that make up the list.

For example:

 <div class="normal">Item 1</div> <div class="normal">Item 2</div> <div class="different">Item 3</div> <div class="different">Item 4</div> <div class="normal">Item 5</div> <div class="normal">Item 6</div> <div class="different">Item 7</div> <div class="different">Item 8</div> 

In this example, I would like to target all instances of <div class="different"> - I used a lot of nth-child generators to come up with an answer, but nothing brings me to what I need.

Any help would be greatly appreciated!

+8
css css-selectors
source share
1 answer

Use div:nth-child(4n-1), div:nth-child(4n) . The logic is simple: you want to select items in groups of four , so 4n will be a common denominator. Since you want to select the penultimate and last elements in the group, 4n-1 and 4n would do the job accordingly.

As follows, a simple diagram illustrating my point:

 #1 #2 #3 <- 4th item - 1 #4 <- 4th item #5 #6 #7 <- 4th item -1 #8 <- 4th item 

 div:nth-child(4n-1), div:nth-child(4n) { background-color: #eee; } 
 <div class="normal">Item 1</div> <div class="normal">Item 2</div> <div class="different">Item 3</div> <div class="different">Item 4</div> <div class="normal">Item 5</div> <div class="normal">Item 6</div> <div class="different">Item 7</div> <div class="different">Item 8</div> 
+14
source share

All Articles