ShibinRagh
ShibinRagh

Reputation: 6646

Reverse the even-odd pattern after every nth-child item

I have a HTML structure showing 4 blocks in each row and the blocks' background color are set as CSS even and odd (Red and Green).

Is it possible to change Even and Odd TO Odd and Even after every forth item?

JSFiddle here

Note: We can't change the HTML structure.

<ul>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
</ul>

Upvotes: 2

Views: 1947

Answers (1)

Harry
Harry

Reputation: 89750

Is it possible to change Even and Odd TO Odd to Even after every forth item?

If you mean that for the first 4 elements the odd elements should have red background while the even ones should have green background and it gets swapped for every set of 4 elements then you can do it using nth-child selectors like in the below snippet. It can be done using nth-of-type also.

ul{
  padding:0;
  width:100%;
}
li{
  width:25%;
  height:50px;
  float:left;
  border:1px solid black;
  list-style:none;
  box-sizing: border-box;
}
li:nth-child(8n+1),li:nth-child(8n+3), li:nth-child(8n+6), li:nth-child(8n){
  background: red;
}
li:nth-child(8n+2),li:nth-child(8n+4), li:nth-child(8n+5), li:nth-child(8n+7){
  background: green;
}
<ul>
<li>bg color RED</li>
<li>bg color Green</li>
<li>bg color RED</li>
<li>bg color Green</li>
<li>bg color Green</li>
<li>bg color RED</li>
<li>bg color Green</li>
<li>bg color RED</li>
<li>bg color RED</li>
<li>bg color Green</li>
<li>bg color RED</li>
<li>bg color Green</li>
</ul>


Or, if you mean to say that for the first four elements the odd elements should have red background while the even ones have green background and after that (that is, from the 5th element on), the odd elements should have green background while the even elements should have red background then you could do it like in the below snippet.

ul {
  padding: 0;
  width: 100%;
}
li {
  width: 25%;
  height: 50px;
  float: left;
  border: 1px solid black;
  list-style: none;
  box-sizing: border-box;
}
li:nth-child(2), li:nth-child(4), li:nth-child(2n+5) {
  background: green;
}
li:nth-child(1), li:nth-child(3), li:nth-child(2n+6) {
  background: red;
}
<ul>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>
  <li>bg color Green</li>
  <li>bg color RED</li>  
</ul>

Upvotes: 3

Related Questions