Apply CSS for n-items

Viewed 70

I have a html structure as below

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

How can I apply styles for like the first 2 items one style and succeeding 2 another style? The 2 divs after the 4th one will have the same styles as 1st two and the patterns goes on.

3 Answers

As suggested by @Chris G as well, you can use a :nth-child(4n + k) selector:

div:nth-child(4n + 1), div:nth-child(4n + 2)  {
  color: green;
}

div:nth-child(4n + 3), div:nth-child(4n) {
  color: red;
}
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
<div>G</div>
<div>H</div>
<div>I</div>
<div>J</div>

If I am understanding you properly it should look something like this:

/* style 1 */
.rows > *:nth-child(4n+1),
.rows > *:nth-child(4n+2){
 color: red;
}
/* style 2*/
.rows > *:nth-child(4n+3),
.rows > *:nth-child(4n+4){
 color: blue;
}
<div class="rows">
    <div>1: style 1</div>
    <div>2: style 1</div>
    <div>3: style 2</div>
    <div>4: style 2</div>
    <div>5: style 1</div>
    <div>6: style 1</div>
    <div>7: style 2</div>
    <div>8: style 2</div>
</div>

The key to nth-child is understanding the equation for it. Think of it as a loop, n equals the iterator of the loop and if it evaluates above 0, it will affect that element.

4n+1

  • 4*0+1 = 1
  • 4*1+1 = 5

The child elements 1 and 5 will both be targeted by the css.

4n+2

  • 4*0+2 = 2
  • 4*1+2 = 6

Here the child elements 2 and 6 will be targeted.

Adding these to together will give us 1,2,5,6 that are all targeted by the same css.

/* style 1 */
.rows > *:nth-child(4n+1),
.rows > *:nth-child(4n+2){
 color: red;
}

This will solve Achieve Your Purpose....But Not much Efficient

const divs = [...document.querySelectorAll('div')]

divs.forEach((el, i) => {
    if (i % 3 == 0 || i % 3 == 1 || i % 3 == 2 ) el.style.backgroundColor = 'red'
    if (i % 4 == 2 || i % 4 == 3) el.style.backgroundColor = 'blue'
})
Related