CSS - 如何为奇数和偶数div着色?

时间:2017-09-27 21:33:51

标签: html css css-selectors

我想使用CSS来实现以下效果,而不需要像那样硬编码。



.colour-blue {
  color:blue;
}
.colour-light-blue {
  color:lightblue;
}

<div class="activeContent">
  <div class="content">
    <div class="colour-blue">
      odd div
    </div>
  </div>
  <div class="content">
    <div class="colour-light-blue">
      even div
    </div>
  </div>
  <!-- and more (content) div -->
</div>
&#13;
&#13;
&#13;

如何使用纯CSS做到这一点?我想避免手动为每个div分配颜色类

2 个答案:

答案 0 :(得分:13)

您可以这样做:

.content:nth-child(odd)>div {
  background: blue;
}

.content:nth-child(even)>div {
  background: red;
}

.content {
  width: 200px;
  height: 200px;
}
<div class="activeContent">
  <div class="content">
    <div class="colour-blue">
      stuff
    </div>
  </div>

  <div class="content">
    <div class="colour-light-blue">
      some more stuff
    </div>
  </div>
</div>

我认为这会很好用。

答案 1 :(得分:6)

你可以试试这个:

.activeContent div.content:nth-child(2n) {
  color: #00ff00;
}

.activeContent div.content:nth-child(2n+1) {
  color: #0000ff;
}
<div class="activeContent">
  <div class="content">
    stuff
  </div>

  <div class="content">
    some more stuff
  </div>
  
  <div class="content">
    more and more stuff
  </div>
  
  <div class="content">
    one more stuff
  </div>
</div>