0

I have the following style block:

@keyframes flip {
  0% {
    transform: rotateX(0);
  }

  50% {
    transform: rotateX(90deg);
    background-color: UNKNOWN;
  }

  100% {
    transform: rotateX(0);
  }
}

For the animation to work nicely, I need to change the background color at 50%. The problem is that some JavaScript function will decide what that color should be. Is accessing the stylesheet with JavaScript my only option to deal with such a case?

Edit


Suppose I have three objects next to each other, and they independently obtain their color through some JavaScript function. How does CSS var() deal with that?

blackened
  • 861
  • 10
  • 19

1 Answers1

3

Use CSS var() with a default defined in your :root css, and using Javascript to set a new value


Demo were the initial value of --background-color is orange, then after 2 seconds we use Javascript to alter it to blue

setTimeout(() => {
  const e = document.querySelector('.animate');
  e.style.setProperty('--background-color', 'blue');
}, 2000); 
:root {
    --background-color: orange;
}

@keyframes flip {
  0% {
    transform: rotateX(0);
  }

  50% {
    transform: rotateX(90deg);
    background-color: var(--background-color);
  }

  100% {
    transform: rotateX(0);
  }
}

.animate {
  animation: flip 5s infinite;
  
  width: 100vw;
  height: 100vh;
} 
<div class="animate" />
0stone0
  • 34,288
  • 4
  • 39
  • 64