Flash CSS colour between previous colour and new c

2019-07-10 05:01发布

Suppose I have a div with a colour added with background-color:red or green. I want to make this flash another colour, where the 'non-flash' is the previous colour value.

HTML
<div class='red make-green flash'></div>

LESS
.red{
  background-color:red;
  .make-green{
    background-color:green;
  }
}
.flash{
   animation: flash 2s infinite;
}
@keyframes flash {
 0%{
    background-color:blue;
 }
 50%{
    background-color:            ;<-- what goes here?
 }
 100%{
    background-color:blue;
 }
}

If we remove .make-green the div should flash red | blue, with the make-green it would flash green | blue.

标签: html css less
2条回答
倾城 Initia
2楼-- · 2019-07-10 05:38

You could use css variables, if you are okay with the non-perfect browser support.

:root {
  --bg: red;
}

.red {
  height: 100px;
  width: 100px;
  background-color: var(--bg);
}

.make-green {
  --bg: green;
}

.flash {
  animation: color 2s infinite;
}

@keyframes color {
  0% {
    background-color: blue;
  }
  50% {
    background-color: var(--bg);
  }
  100% {
    background-color: blue;
  }
}
<div class='red make-green flash'></div>
<div class='red flash'></div>

查看更多
成全新的幸福
3楼-- · 2019-07-10 05:55

Here is another idea without CSS variables where you can slightly change the animation to consider the initial state of the element. Without specifying the 100% state the browser will automatically consider the value specified inside the element.

.red {
  background-color: red;
}

.make-green {
  background-color: green;
}


.flash {
  animation: flashE 1s infinite alternate;
}

@keyframes flashE {
  0% {
    background-color: blue;
  }
}
<div class='red flash'>Some text</div>

<div class='red make-green flash'>Some text</div>

查看更多
登录 后发表回答