html
<div class="box">
动态渐变边框
</div>
css
<style>
html,
body {
height: 100vh;
width: 100vw;
display: flex;
align-items: center;
justify-content: center;
}
body {
background-color: #313131;
}
.box {
width: 400px;
height: 300px;
background-color: #222;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: #fff;
font-weight: 800;
}
.box {
position: relative;
/* 设置相对定位以后,子元素中的绝对定位范围会在该div内 */
}
.box::before {
content: "";
position: absolute;
left: -20px;
top: -20px;
width: calc(100% + 40px);
/* calc方法可以用来动态计算长度 */
height: calc(100% + 40px);
border-radius: 10px;
z-index: -1;
background-image: linear-gradient(135deg,
#ff0000,
#ff7f00,
#ffff00,
#00ff00,
#00ffff,
#0000ff,
#8b00ff);
background-size: 400%;
/* 背景放大,动画更明显 */
animation: animate_box 5s linear infinite;
}
@keyframes animate_box {
0%,
100% {
background-position: 0%, 50%;
}
50% {
background-position: 100%, 50%;
}
}
</style>