生成动画彩虹边框

Generating an animated rainbow border

我一直在使用 background-image CSS 属性 来创建这样的彩虹边框:

.rainbow {
  border: double 0.3em transparent;
  border-radius: 10px;
  background-image: linear-gradient(white, white), 
  linear-gradient(to right, rgb(235, 50, 235), rgb(82, 82, 209));
  background-origin: border-box;
  background-clip: content-box, border-box;
}
<div class="rainbow">Example</div>

并希望将其制作成动画。是否可以制作动画 background-image,如果可以,如何使用?

我能够通过将背景位置设置为偏移动画来实现此功能,当动画在我的浏览器上重置时会出现轻微的闪烁,但您可以通过使用较大的 vh 值来降低闪烁频率,并且它只有在厚元素上才真正引人注目(或者当你有像 border 3em 这样的东西时)

    /*animate the background gradient position, use vh so that start/end syncs up viewport horizontal*/
@keyframes rainbow {
    from {background-position: -100vh 0}
    to {background-position: 100vh 0}
} 

/*compatibility*/
@-moz-keyframes rainbow {
    from {background-position: -100vh 0}
    to {background-position: 100vh 0}
}
@-webkit-keyframes rainbow {
    from {background-position: -100vh 0}
    to {background-position: 100vh 0}
}
@-ms-keyframes rainbow {
    from {background-position: -100vh 0}
    to {background-position: 100vh 0}
}
@-o-keyframes rainbow {
    from {background-position: -100vh 0}
    to {background-position: 100vh 0}
}

 .rainbow {
  border: double 0.3em transparent;
  border-radius: 10px;
     /*added a colourstop here, without the third colourstop you get a hard edge*/
  background: linear-gradient(white, white), 
  repeating-linear-gradient(to right, rgb(82, 82, 209),rgb(235, 50, 235), rgb(82, 82, 209));
  background-origin: border-box;
  background-clip: content-box, border-box;


            animation-name: rainbow;
            animation-duration:  3s;

            /*set animation to continue forever, and to move at a single rate instead of easing*/
            animation-iteration-count: infinite;
            animation-timing-function: linear;
}

希望对您有所帮助!