CSS发光边框动画过渡不流畅,如何实现平滑过渡?
解决CSS发光边框动画过渡断层问题
问题原因
动画出现断层的核心原因:
- 线性渐变的颜色序列首尾不匹配,循环时结尾与开头颜色无法自然过渡
background-position的动画终点和background-size比例不协调,导致背景画面循环时无法无缝衔接
修复方案
- 调整渐变颜色序列:让序列首尾颜色一致,形成循环的色彩流
- 匹配背景尺寸与动画参数:使动画结束时背景位置刚好移动完整的背景尺寸,实现无缝循环
修改后的完整代码
* { margin: 0; padding: 0; } body { height: 100vh; display: flex; align-items: center; justify-content: center; background: #151320; } .box { position: relative; width: 300px; height: 300px; color: #fff; font: 300 2rem 'Montserrat'; text-align: center; text-transform: uppercase; display: flex; align-items: center; } .box::before, .box::after { content: ''; z-index: -1; position: absolute; width: calc(100% + 30px); height: calc(100% + 30px); top: -15px; left: -15px; /* 调整渐变序列,首尾统一为#0096FF,实现色彩循环衔接 */ background: linear-gradient(45deg, #0096FF, #0047AB, #000000, #6082B6, #87CEEB, #00008B, #145DA0, #00008B, #145DA0, #0096FF, #0047AB, #000000, #6082B6, #87CEEB, #0096FF); background-repeat: repeat; border-radius: 5px; /* 调整背景大小为500%,配合动画位置实现无缝循环 */ background-size: 500%; animation: border 12s linear infinite; } .box::after { filter: blur(25px); } /* 动画位置从0%到100%,对应背景大小的完整移动 */ @keyframes border { 0% { background-position: 0% 0%; } 100% { background-position: 100% 0%; } }
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet'> <div class='box'> Greetings fellow developer! </div>
额外说明
如果想保留对角线方向的动画效果,只需调整动画的background-position终点为100% 100%即可,同样能实现无缝过渡:
@keyframes border { 0% { background-position: 0% 0%; } 100% { background-position: 100% 100%; } }
内容的提问来源于stack exchange,提问作者Beru
相关产品推荐
相关产品推荐

