我想使用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;
如何使用纯CSS做到这一点?我想避免手动为每个div分配颜色类
答案 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>