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
.
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>
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>