我需要为多个 div 设置一个类,并且每个 div 都有不同的背景颜色。
<div class="genericClass">Some Text</div> <!-- This should be #000 -->
<div class="genericClass">Some Text</div> <!-- This should be #FFF -->
<div class="genericClass">Some Text</div> <!-- This should be #B1B -->
<div class="genericClass">Some Text</div> <!-- This should be #DDD -->
.genericClass{
background-color: #000; /* this should be the first */
background-color: #FFF; /* this should be the second */
background-color: #B1B; /* this should be the third */
background-color: #DDD; /* this should be the fourth */
}
但我不知道如何才能做到这一点。
编辑:我没有机会知道可以添加多少个元素,因此,该模式应在四个 div 后重复,因此,如果有五个 div,最后一个应采用 #000(第一个)颜色。
最佳答案
您可以使用 :nth-of-type(n) 选择器以特定顺序/位置选择元素
要让颜色重复,您可以使用以下语法:4n + x,其中 4 是循环大小,因此该序列每 4 个元素重复一次,x 是偏移量+ 1 定位第一个元素 + 2 定位第二个元素,依此类推。
进一步引用:w3schools.com :nth-child() Selector
.genericClass:nth-of-type(4n + 1) {
background-color: #000; //this should be the first
}
.genericClass:nth-of-type(4n + 2) {
background-color:#FFF; //this should be the second
}
.genericClass:nth-of-type(4n + 3) {
background-color: #B1B; //this should be the third
}
.genericClass:nth-of-type(4n + 4) {
background-color: #DDD; //this should be the fourth
}
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
<div class="genericClass">Some Text</div>
<!-- This should be #000 -->
<div class="genericClass">Some Text</div>
<!-- This should be #FFF -->
<div class="genericClass">Some Text</div>
<!-- This should be #B1B -->
<div class="genericClass">Some Text</div>
<!-- This should be #DDD -->
关于html - CSS - 多个 div 的相同类和先前设置的不同颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183704/