首页 > 解决方案 > CSS 边框图像关键帧动画在 Firefox 中有效,但在 Chrome 中无效

问题描述

我有div一个渐变border-image和一个animation改变deg关键帧中渐变(度数)的属性。

这在 Firefox 中完美运行,但在 Chrome 中却不行。事实上,在 Chrome 中,元素根本没有边框。animation就像浏览器在看到元素具有属性时简单地放弃一样。

这是一个小提琴:

https://jsfiddle.net/0nymc9ej/2/

body {
  background: black;
}

div {
  color: white;
  width: 300px;
  height: 300px;
  border: 5px solid;
  border-image: linear-gradient(0deg, #ff0000, #00ff00, #0000ff) 1 / 5px;
  animation: move 1s infinite;
}

@keyframes move {
    0%   { border-image: linear-gradient(0deg, #ff0000, #00ff00, #0000ff) 1 / 5px; }
  25%  { border-image: linear-gradient(90deg, #ff0000, #00ff00, #0000ff) 1 / 5px; }
  50%  { border-image: linear-gradient(180deg, #ff0000, #00ff00, #0000ff) 1 / 5px; }
  75%  { border-image: linear-gradient(270deg, #ff0000, #00ff00, #0000ff) 1 / 5px; }
  100% { border-image: linear-gradient(360deg, #ff0000, #00ff00, #0000ff) 1 / 5px; }
}
<div>This has a nice moving border in Firefox but not in Chrome</div>

  1. 为什么这在 Chrome 中不起作用,但在 Firefox 中起作用?
  2. 有什么方法可以在不使用伪元素、JavaScript 或其他 hacky 方式的情况下在 Chrome 中工作?
  3. 有没有办法让渐变变化“淡化”到彼此平滑(无需简单地添加更多关键帧),因为动画现在看起来真的很生涩?

标签: htmlcssgoogle-chromefirefox

解决方案


这是一个使用面具的想法:

body {
  background: black;
}
.box {
  color: white;
  width: 300px;
  height: 200px;
  position:relative;
  padding:5px; /* this will control the border width */
  overflow:hidden;
}
.box div{
  content:"";
  position:absolute;
  inset:0; /* shorthand of top right bottom left */
  padding: inherit;
  /* make the gradient visible only inside the padding area */
  -webkit-mask:
    linear-gradient(#fff 0 0) content-box,
    linear-gradient(#fff 0 0) padding-box;
  -webkit-mask-composite:destination-out;
  mask-composite:exclude;
  /**/
}
/* a rotating gradient layer */
.box div::before{
  content:"";
  position:absolute;
  inset:-50%;
  background:linear-gradient(#ff0000, #00ff00, #0000ff);
  animation: move 1s infinite;
}
@keyframes move {
  100% { transform:rotate(360deg); }
}
<div class="box">
 <div></div>
This has a nice moving border</div>

在不久的将来,您可以使用下面的 CSS 变量来实现(目前仅适用于 Chrome 和 edge)

@property --a{
  syntax: '<angle>';
  inherits: false;
  initial-value: 0deg;
}

body {
  background: black;
}

div {
  color: white;
  width: 300px;
  height: 200px;
  border: 5px solid;
  --a:0deg; /* fallback for FF to see the border */
  border-image: linear-gradient(var(--a), #ff0000, #00ff00, #0000ff) 1 / 5px;
  animation: move 1s infinite;
}

@keyframes move {
   100%{--a:360deg}
}
<div>This has a nice moving border</div>


推荐阅读