htmlcssjquery-animate

Animating progress bars with CSS


So, I have a few different progress bars on this page - http://kaye.at/play/goals

Here's my HTML & CSS:

<div class="meter"><span style="width: 100%;"></span></div>


.meter { 
height: 5px;
position: relative;
background: #f3efe6;
z-index: 0;
margin-top: -5px;
overflow: hidden;
}

.meter > span {
z-index: 50;
display: block;
height: 100%;
background-color: #e4c465;
position: relative;
overflow: hidden;
}

I want to simply animate the progress bar so that it slowly goes up from 0% to whatever percentage it's at, rather than just appearing there, but I'd like to do it in the simplest way possible. What's my best option and is it possible with the current code I'm using?


Solution

  • The only way I can think to animate to your width set inline is to add another span, so the HTML ends up as:

    <div class="meter">
        <span style="width:80%;"><span class="progress"></span></span>
    </div>
    

    That extra span is needed, as we have no way (using just CSS) of checking what the inline style wants the width to be and so animating to it. And unfortunately we can't animate to auto.

    Here is a snippet:

    .meter { 
        height: 5px;
        position: relative;
        background: #f3efe6;
        overflow: hidden;
    }
    
    .meter span {
        display: block;
        height: 100%;
    }
    
    .progress {
        background-color: #e4c465;
        animation: progressBar 3s ease-in-out;
        animation-fill-mode:both; 
    }
    
    @keyframes progressBar {
      0% { width: 0; }
      100% { width: 100%; }
    }
    <div class="meter">
        <span style="width:80%;"><span class="progress"></span></span>
    </div>

    You can see this in action here. Browsers that don't support CSS animations will just get the bar in its final state.