CSS 边框透明度动画



我是CSS的新手。这是我的代码:

.border1{
border-bottom: 5px solid rgb(255, 0, 0,0.5);
animation-name: animation;
animation-duration: 4s;
}
.border2{
border-bottom: 5px solid rgb(0, 255, 0,0.5);
animation-name: animation;
animation-duration: 4s;
}

和动画:

@keyframes animation {
from {border-bottom-color: rgba(0, 255, 0, 0);}
to {border-bottom-color: rgba(0, 255, 0, 0.5);}
}

此动画仅适用于边框 2,因为边框 2 为绿色,但边框 1 为红色。我不想为代码中的每个边框编写动画关键帧。

所以我想做这样的事情:

@keyframes animation {
from {border-bottom-color: rgba(, , , 0);}
to {border-bottom-color: rgba(, , , 0.5);}
}

只需更改不透明度并保留默认颜色。如果可能的话,请告诉我如何。

使用 CSS 变量:

.border {
border-bottom: 5px solid rgba(var(--c),0.5);
animation: animation 4s infinite alternate linear;
height:20px;
}
.border1{
--c:255,0,0;
}
.border2{
--c:0,255,0;
}
@keyframes animation {
from {border-bottom-color: rgba(var(--c), 0);}
to {border-bottom-color: rgba(var(--c), 0.5);}
}
<div class="border border1"></div>
<div class="border border2"></div>

另一个想法是使用伪元素来模拟边框,然后您可以对不透明度进行动画处理:

.border {
position:relative;
height:20px;
}
.border:before {
content:"";
position:absolute;
bottom:0px;
left:0;
right:0;
height:5px;
animation: animation 4s infinite alternate linear;
}
.border1:before{
background:red;
}
.border2:before{
background:green;
}
@keyframes animation {
from {opacity:0;}
to {opacity:0.5;}
}
<div class="border border1"></div>
<div class="border border2"></div>

最新更新