CSS背景渐变发光动画

时间:2019-05-05 07:23:14

标签: html css css-animations linear-gradients

我想创建一个加载动画的动画,该动画将出现在具有不同背景颜色的多个元素上。

当前,我正在使用background-image渐变色,并且正在使用background-position单位为vw设置动画,但是它不可缩放,我的元素将具有不同的长度。

是否可以使用百分比单位为background-image设置动画?

创建的动画

body {
  background: black;
}

header {
  width: 100%;
  height: 50px;
  background-color: rebeccapurple;
  background-image: linear-gradient(
    to right,
    transparent 0%,
    rgba(255,255,255,0.3) 50%,
    transparent 100%
  );
  background-repeat: no-repeat;
  background-position: -100vw;
  animation: shine 2s infinite;
}

@keyframes shine {
  0% {
    background-position: -100vw;    
  }
  100% {
    background-position: 100vw;   
  }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>  
</head>
<body>
  
  <header></header>
  

</body>
</html>

1 个答案:

答案 0 :(得分:2)

一个想法是使渐变的大小比容器大3倍,并对它的中间部分进行着色,然后从左向右滑动它:

enter image description here

body {
  background: black;
}

.box {
  height: 50px;
  margin:5px;
  background-color: rebeccapurple;
  background-image: linear-gradient(
    to right,
    transparent 33%,
    rgba(255,255,255,0.3) 50%,
    transparent 66%
  );
  background-size:300% 100%;
  animation: shine 2s infinite;
}

@keyframes shine {
  0% {
    background-position: right;    
  }
  /*100% {
    background-position: left; it's the default value, no need to define it
  }*/
}
<div class="box"></div>

<div class="box" style="width:60%"></div>

<div class="box" style="width:40%"></div>

相关问题:Using percentage values with background-position on a linear gradient