CSS|彩虹特效中的小知识

251 阅读2分钟

首先我们写一下html代码,红橙黄绿青蓝紫一共有7道,我们创建7个div

<!-- 用--index作为标号来区分不同的彩虹 -->
  <div class="rainbow">
    <div class="rainbow__band" style="--index: 0;"></div>
    <div class="rainbow__band" style="--index: 1;"></div>
    <div class="rainbow__band" style="--index: 2;"></div>
    <div class="rainbow__band" style="--index: 3;"></div>
    <div class="rainbow__band" style="--index: 4;"></div>
    <div class="rainbow__band" style="--index: 5;"></div>
    <div class="rainbow__band" style="--index: 6;"></div>
  </div>

接下来让我们来写css代码:

    * {
      /* 为了方便计算我们使用 box-sizing 定义了该如何计算一个元素的宽高 */
      box-sizing: border-box;
    }
    
    /* 定义容器的大小,内部使用绝对定位,参考系为该容器 */
    .rainbow {
      height: 25vmin;
      width: 50vmin;
      position: relative;
      overflow: hidden;
    }
    
    .rainbow__band {
    /* 定义各自的宽度,通过index,还要对应下面的border-width */
      --size: calc((50 - (var(--index, 0) * 6)) * 1vmin);
      height: 50vmin;
      width: 50vmin;
      border-radius: 50%;
      /* 参照父元素进行定位 */
      position: absolute;
      top: 100%;
      left: 50%;
      /* 设置border的width,注意最外层已经使用 box-sizing: border-box; 定义了元素的width */
      border-width: 3vmin;
      border-style: solid;
      /* 不通的彩虹显示不同的颜色:hsl(x,y,z),x不同可以代表不同的颜色 */
      border-color: hsl(var(--hue, 10), 80%, 50%);
      transform: translate(-50%, -50%);
      height: var(--size);
      width: var(--size);
    }
    
    /* 给不同的彩虹道显示不同的颜色 */
    .rainbow__band:nth-of-type(2) {
      --hue: 35;
    }
    .rainbow__band:nth-of-type(3) {
      --hue: 55;
    }
    .rainbow__band:nth-of-type(4) {
      --hue: 110;
    }
    .rainbow__band:nth-of-type(5) {
      --hue: 200;
    }
    .rainbow__band:nth-of-type(6) {
      --hue: 230;
    }
    .rainbow__band:nth-of-type(7) {
      --hue: 280;
    }
    
    .rainbow__band {
      border-color: hsl(var(--hue, 10), 80%, 50%);
      animation: rainbow 3s calc(var(--index, 0) * -0.2s) infinite linear;
    }
    
    /* 给动画添加关键帧,改变对应的颜色 */
    @keyframes rainbow {
      0%, 100% {
        --hue: 10;
      }
      14% {
        --hue: 35;
      }
      28% {
        --hue: 55;
      }
      42% {
        --hue: 110;
      }
      56% {
        --hue: 200;
      }
      70% {
        --hue: 230;
      }
      84% {
        --hue: 280;
      }
    }  

最后的效果就是:

2021-08-18 00-03-29.2021-08-18 00_03_49.gif

通过该项目主要是又重新复习了css一些属性:

  • box-sizing:定义了计算机程序(一般指浏览器)应该如何计算一个元素的总宽度和总高度
  • transform:允许你旋转,缩放,倾斜或平移给定元素
  • animation:动画相关
  • @keyframes:通过在动画序列中定义关键帧(或waypoints)的样式来控制CSS动画序列中的中间步骤

还有CSS中的一些单位:比如vmin...,具体的可以参考传送门 写业务写久了,好多东西都已经忘记了 0.0