Use different @keyframes based on parent element class

非 Y 不嫁゛ 提交于 2020-01-11 09:46:12

问题


I have an animation like below:

@keyframes pulseColorGreen {
    0% {
        background-color: green;
    }
    97%{
        background-color: green;
    }
    100% {
      background-color: white;
    }
  }

My website also has a dark mode where the background goes black. Now in the animation, I want to display a darker green just like below:

@keyframes pulseColorGreen {
    0% {
        background-color: darkgreen;
    }
    97%{
        background-color: darkgreen;
    }
    100% {
      background-color: black;
    }
  }

For the dark mode, I add a class "lightsOff" in the body tag. I am managing all other color changes using the combination of the target element class and "lightsOff" class just like:

.lightsOff .someclass{
    color: white
}

But when defining an element in css file as:

@keyframes .lightsOff pulseColorGreen {
    0% {
        background-color: darkgreen;
    }
    97%{
        background-color: darkgreen;
    }
    100% {
      background-color: black;
    }
  }

It gives me error saying "identifier expected". I am adding the animation-name property to elements dynamically from javascript. Hence, I won't prefer changing the JS code to identify which theme is set currently and set a keyframe accordingly. How can I achieve this?


回答1:


You can use CSS variable and you will need only one keyframes that you don't have to change. Simply change the main class that define the color:

.light {
  --c: yellow;
}

.dark {
  --c: darkblue;
}

.box {
  height: 100px;
  margin: 5px;
  box-shadow: 0 0 5px var(--c);
  color:#fff;
  animation: pulseColorGreenMkt 1s infinite linear alternate;
}

@keyframes pulseColorGreenMkt {
  0% {
    background-color: var(--c);
  }
  100% {
    background-color: black;
  }
}
<div class="box light">
  Class defined on the element
</div>
<div class="dark">
  <div class="box">
    Class defined on a parent element
  </div>
</div>


来源:https://stackoverflow.com/questions/51580920/use-different-keyframes-based-on-parent-element-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!