Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

This displays like

A B
C D
E F 
G H 
I J

Which is good, however, I want the background colors to be like

red blue
blue red
red blue
blue red
red blue

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

like image 320
omega Avatar asked Mar 10 '23 16:03

omega


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>
like image 110
MarcinJuraszek Avatar answered Mar 24 '23 03:03

MarcinJuraszek


Check this out:

#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>
like image 40
Miro Avatar answered Mar 24 '23 03:03

Miro