效果图
实现原理
给字体盒子添加伪元素::after,通过定位定在盒子上,设置宽高,添加背景色为渐变色,添加动画,移动渐变色背景的background-position.
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
/* 盒子外部居中 */
margin: 0 auto;
margin-top: 200px;
position: relative;
--borderWidth: 3px;
color: white;
/* 自定义属性 */
--borderWidth: 5px;
/* var(value)可以调用的属性值 */
border-radius: var(--borderWidth);
background: #000;
}
div::after {
content: "";
position: absolute;
/* 通过left负值和top负值,使伪元素盒子遮盖父盒子 */
top: calc(-1 * var(--borderWidth));
left: calc(-1 * var(--borderWidth));
/* 设置宽高为父盒子的宽高加上左右上下边框值 */
height: calc(100% + var(--borderWidth) * 2);
width: calc(100% + var(--borderWidth) * 2);
/* 设置线性渐变色 */
background: linear-gradient(60deg, #f79533, #f37055, #ef4e7b, #a166ab, #5073b8, #1098ad, #07b39b, #6fba82);
/* 设置伪元素位于父盒子之下 */
z-index: -1;
/* 设置伪元素盒子背景色尺寸便于位移 */
background-size: 300% 300%;
border-radius: calc(2 * var(--borderWidth));
/* 设置动画位移背景图,也就是背景色 */
animation: animatedGradient 3s linear alternate infinite;
}
@keyframes animatedGradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
</style>
</head>
<body>
<div>
渐变色边框
</div>
</body>
</html>