Jonan
Jonan

Reputation: 2536

Animated progress bar with css

I want the progress bar to go from 0% width to 50% width in 2 seconds. This is my code so far:

<style>  
  #progressbar {
      background-color: #000000;
      border-radius: 8px;
      padding: 3px;
      width: 400px;
    }

    #progressbar div {
       background-color: #0063C6;
       height: 10px;
       border-radius: 5px;
       animation:loadbar 2s;
        -webkit-animation:loadbar 2s;
    }

    @keyframes loadbar {

    0% {
        width: 0%;
    }

    100% {
        width: 50%;
    }

    @-webkit-keyframes loadbar {

    0% {
        width: 0%;
    }

    100% {
        width: 50%;
    }

}
</style>

<div id="progressbar">
    <div></div>
</div>

but when I open the page the width is 100% instead of 50%. what have I done wrong?

Upvotes: 1

Views: 6935

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 240878

jsFiddle demo

Set the initial width to 0%

#progressbar div {
   background-color: #0063C6;
   height: 10px;
   width:0%; /* ADD THIS <<< */
   border-radius: 5px;
   animation:loadbar 2s;
   -webkit-animation:loadbar 2s;
   -webkit-animation-fill-mode: forwards;
   animation-fill-mode: forwards;
}  

Additionally, I added in the following..

   -webkit-animation-fill-mode: forwards;
   animation-fill-mode: forwards;

If you want the animation to end in a forwards motion you need this... here is a demo demonstrating what would happen without it.. jsFiddle here

Upvotes: 1

aCodeSmith
aCodeSmith

Reputation: 552

Your loadbar animation was not closed. The animation should work now. I've also added a forwards keyword to only play the animation once.

#progressbar {
  background-color: black;
  border-radius: 8px;
  padding: 3px;
  width: 400px;
}

#progressbar div {
  background-color: #0063C6;
  height: 10px;
  border-radius: 5px;
  animation:loadbar 2s normal forwards ease-in-out;
  -webkit-animation:loadbar 2s normal forwards ease-in-out;
}

@keyframes loadbar {

  0% {
    width: 0%;
  }

  100% {
    width: 100%;
  }
}
@-webkit-keyframes loadbar {

  0% {
    width: 0%;
  }

  100% {
    width: 100%;
  }

}

Upvotes: 2

Milan and Friends
Milan and Friends

Reputation: 5610

Here's a Fiddle

#progressbar div {
   background-color: #0063C6;
   width: 50%;
   height: 10px;
   border-radius: 5px;
   animation:loadbar 2s;
   -webkit-animation:loadbar 2s;
}

@keyframes loadbar {

  0% {
    width: 0%;
  }

  100% {
    width: 50%;
  }
}
@-webkit-keyframes loadbar {

  0% {
    width: 0%;
  }

  100% {
    width: 50%;
  }

}

Upvotes: 1

Related Questions