How to alternate colors in two columns in css3 selector?

If i have this code

#list>div {
  font-size: 18px;
  float: left;
  margin: 0 10px 10px 0;
  width: 150px;
}

#list>div:nth-child(2n+1) {
  clear: left;
}

#list>div:nth-child(odd) {
  background-color: red;
}

#list>div:nth-child(even) {
  background-color: blue;
}
<div id="list">
  <div class="list-item">A</div>
  <div class="list-item">B</div>
  <div class="list-item">C</div>
  <div class="list-item">D</div>
  <div class="list-item">E</div>
  <div class="list-item">F</div>
  <div class="list-item">G</div>
  <div class="list-item">H</div>
  <div class="list-item">I</div>
  <div class="list-item">J</div>
</div>
Run codeHide result

It displays as

A B
C D
E F 
G H 
I J

Ok, however, I want the background colors to look like

red blue
blue red
red blue
blue red
red blue

However, the code above makes each column the same color. Is there a pure-css3 way I can do this?

+4
source share
2 answers

#list>div {
  font-size: 18px;
  float: left;
  margin: 0 10px 10px 0;
  width: 150px;
}

#list>div:nth-child(2n+1) {
  clear: left;
}

#list>div:nth-child(4n+1), #list>div:nth-child(4n) {
  background-color: red;
}

#list>div:nth-child(4n+2), #list>div:nth-child(4n+3) {
  background-color: blue;
}
<div id="list">
  <div class="list-item">A</div>
  <div class="list-item">B</div>
  <div class="list-item">C</div>
  <div class="list-item">D</div>
  <div class="list-item">E</div>
  <div class="list-item">F</div>
  <div class="list-item">G</div>
  <div class="list-item">H</div>
  <div class="list-item">I</div>
  <div class="list-item">J</div>
</div>
Run codeHide result
+6
source

Check this:

#list>div {
  font-size: 18px;
  float: left;
  margin: 0 10px 10px 0;
  width: 150px;
  background-color: red;
}


#list>div:nth-child(4n+1) {
  background-color: blue;
}

#list>div:nth-child(4n) {
  background-color: blue;
}

#list>div:nth-child(2n+1) {
 clear:left 
}
<div id="list">
  <div class="list-item">A</div>
  <div class="list-item">B</div>
  <div class="list-item">C</div>
  <div class="list-item">D</div>
  <div class="list-item">E</div>
  <div class="list-item">F</div>
  <div class="list-item">G</div>
  <div class="list-item">H</div>
  <div class="list-item">I</div>
  <div class="list-item">J</div>
</div>
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1671833/


All Articles