如何只用 css 循环一组颜色?

rt, 我想只用 css 循环一组颜色作为一组 div 的背景,

大概样子就是这样

红 蓝 绿 黄 红
蓝 绿 黄 红 蓝
绿

四个颜色,按照顺序循环。

ps: 我尝试使用 nth-child 没有能解决。

阅读 10.4k
6 个回答

试了下 nth-child 应该是可以的。参考:

<div class="total-container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <!-- ... -->
</div>
.item{
    height: 20px;
    margin-bottom: 10px;
}
.item:nth-child(4n+1){
    background: red;
}
 .item:nth-child(4n+2){
    background: blue;
}
 .item:nth-child(4n+3){
    background: green;
}
 .item:nth-child(4n+4){
    background: yellow;
}

要点是这个n,它是非负整数,可以取0。

:nth-child(4n - 3)
:nth-child(4n - 2)
:nth-child(4n - 1)
:nth-child(4n)

……我知道用预处理的可以,粘贴了一份sass的使用方法

/sass style
//-------------------------------
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

//css style
//-------------------------------
.item-1 {
  width: 2em; 
}
.item-2 {
  width: 4em; 
}
.item-3 {
  width: 6em; 
}

下面是一个div的思路,一组div也差不多

<html>
<head>
  <style>
  div {
    width: 160px;
    height: 100px;
    animation: colorful 5s infinite;
  }
  @keyframes colorful {
    0% {
      background: red;
    }
    25% {
      background: blue;
    }
    50% {
      background: green;
    }
    75% {
      background: yellow;
    }
    100% {
      background: red;
    }
  }
</style>
</head>
  <div></div>
</html>

你是要给多个div渲染北京颜色嘛??我理解是这样的,也就是有100个div,用四种颜色去寻欢加载这100个div是这样嘛?
那么一楼的方法是正确的
2n代表偶数,2n-1代表奇数 说白了就是数学公式
图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题