gamer merch
gamer merch

Reputation: 93

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

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

Upvotes: 1

Views: 141

Answers (2)

Faiz Sulistiyo
Faiz Sulistiyo

Reputation: 11

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 class="wrapper">
<div class="bar"></div>
</div>

Upvotes: 1

DevAbdoTolba
DevAbdoTolba

Reputation: 127

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

Upvotes: 2

Related Questions