我想创建一个闪光加载动画,它将出现在具有不同背景颜色的多个元素上。
目前,我正在使用 background-image
渐变,我正在使用 vw
单位为 background-position
设置动画,但它不是可扩展,我的元素将有不同的长度。
有没有一种方法可以用百分比单位为 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;
}
}
<header></header>
最佳答案
一个想法是让渐变的大小比容器大 3 倍,然后为它的中间部分着色,然后从左向右滑动它:
body {
background: black;
}
.box {
height: 50px;
margin:5px;
background:
linear-gradient(90deg,#0000 33%,rgba(255,255,255,0.3) 50%,#0000 66%)
rebeccapurple;
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>
不同动画的另一种选择:
body {
background: black;
}
.box {
height: 50px;
margin:5px;
background:
repeating-linear-gradient(90deg,#0000 0,rgba(255,255,255,0.3) 25%,#0000 50%)
rebeccapurple;
background-size:200% 100%;
animation: shine 1s infinite linear;
}
@keyframes shine {
0% {
background-position: right;
}
}
<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
关于html - 使用线性渐变作为背景的响应式闪耀动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657657/