CSS 动画保留原始属性

CSS Animation Preserve Original Properties

我有这个 CSS 以背景颜色开始并过渡到原始背景颜色的动画:

@high-light-white: #ffffff;
@high-light-yellow: #ede5d0;
@high-light-default: #dce1ea;
@high-light-duration: 10s;

.highlight-comment {
    -webkit-animation-name: highlight; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: @high-light-duration; /* Safari 4.0 - 8.0 */
    animation-name: highlight;
    animation-duration: @high-light-duration;
}
@keyframes highlight {
    from {
        background-color: @high-light-yellow;
    }
    to {
        background-color: @high-light-default;
    }
}

我的问题是我有另一个元素想使用同样的 CSS,但它有不同的背景颜色。有没有一种方法可以将它设置为动画,以便在不指定的情况下将过渡设置为原始背景色?

尝试

.div-with-original-background-color {
    background-color: blue;
}
.div-with-another-original-background-color {
    background-color: green;
}

@keyframes highlight {
    from {
        background-color: @high-light-yellow;
    }
    to {
        background-color: transparent;
    }
}

<div class="div-with-original-background-color">
    <div class="highlight-comment">
       Some Sweet comment...
    </div>
</div>

<div class="div-with-another-original-background-color">
    <div class="highlight-comment">
       foo
    </div>
</div>

CSS变量/Custom properties可以做到。

相同的动画,具有相同的变量,但是该变量在运行时编译,可以通过重新声明它在单个元素上进行更改。

:root {
  --default: blue;
  --highlight: lightyellow;
}

div {
  width: 50%;
  margin: 1em auto;
  border: 1px solid grey;
  height: 50px;
}

.one,
.two {
  background: var(--default);
  animation: highlight 2.5s linear infinite;
}

.two {
  --default: red;
}

@keyframes highlight {
  from {
    background-color: var(--highlight);
  }
  to {
    background-color: var(--default);
  }
}
<div class="one"></div>

<div class="two"></div>

一个想法是在动画中只指定一种颜色,并使其从0%x%然后剩下的将是默认一个:

.box {
  height: 150px;
  background: red;
  animation: anim 2s linear infinite;
}

.box-2 {
  height: 50px;
  background: black;
  animation: anim 2s linear infinite;
}

@keyframes anim {
  0%,
  20% {
    background: blue;
  }
}
<div class="box">

</div>
<div class="box-2">

</div>