如何在css3选择器中的两列中交替颜色?

时间:2017-03-08 18:27:28

标签: html css css3 css-selectors

如果我有这段代码

#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>

显示如

A B
C D
E F 
G H 
I J

哪个好,但是,我希望背景颜色像

red blue
blue red
red blue
blue red
red blue

但是,上面的代码使每列的颜色相同。有没有一种纯粹的css3方法可以做到这一点?

2 个答案:

答案 0 :(得分:6)

pr.key
#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;
}

答案 1 :(得分:1)

检查出来:

#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>