Home > database >  How can I animate the color of this bar in CSS?
How can I animate the color of this bar in CSS?

Time:01-03

I have a depleting bar that I'm trying to animate, but I want to change the color of the bar over time.

I tried doing this:

@keyframes colorChange {
   0% { background-color: green; }
  50% { background-color: yellow; }
  100% { background-color: red; }
}

But it isn't working. How can I fix this? Codepen: https://codepen.io/gamerm83/pen/XWBKYyQ

CodePudding user response:

you should delete, move or combine them.

.round-time-bar[data-style="smooth"] div {
    animation: roundtime calc(var(--duration) * 1s) linear forwards;
}
.round-time-bar div {
  animation: colorChange 1s infinite;
}

The first CSS rule applies an animation called 'roundtime' to all div elements that are inside an element with a class of .round-time-bar and a data-style attribute with the value of 'smooth'. The second CSS rule applies an animation called 'colorChange' to all div elements that are inside an element with a class of .round-time-bar. However, the first rule takes precedence over the second rule, so the animation specified in the first rule will be applied to all div elements that meet the conditions specified in the first rule, regardless of whether they also meet the conditions specified in the second rule.

CodePudding user response:

As Adi L mentioned, you can't combine 2 animations at once eg:-

@keyframes move {
    0%, 100% { transform: translateX(0px); }
    50% { transform: translateX(50px); }
}
@keyframes skew {
    0%, 100% { transform: skewX(0deg); }
    50% { transform: skewX(15deg); }
}
@keyframes opacity {
    0%, 100% { opacity: 1; }
    50% { opacity: .25; }
}

you have to make 3 divs for every keyframe of them

.div_class
{
    animation:animate1 1000ms linear infinite;
}

.element
{     
   animation:animate2 3000ms linear infinite;
}

Src is the accepted answer

So only changing the selector name fixes the problem

here is a fork working perfectly with perfect timing.

edited line 87

.round-time-bar[data-style="smooth"] div.wrapper {
  animation: roundtime calc(var(--duration) * 1s) linear forwards;
}

to

.round-time-bar[data-style="smooth"] {
  animation: roundtime calc(var(--duration) * 1s) linear forwards;
}

This fixed the problem

CodePudding user response:

you need to wrap the bar, and scale the wrapper. for the color change you can apply on .bar

.bar{
width:100%;
height:100%;
animation: anim 1s infinite;
transform-origin:center;
}

@keyframes anim{
0%{
background-color:red
}
50%{
background-color:green
}
100%{
background-color:yellow
}
}
.wrapper{
width:100%;
height:4px;
animation: scale 1s infinite;
}
@keyframes scale{
to{
transform:scaleX(0);
}
}
<div >
<div ></div>
</div>

  •  Tags:  
  • css
  • Related