How to maintain the end state in a CSS Animation

One thing I’ve noticed is that when it comes to CSS Animations a commonly asked question is how to stop a CSS animation at the end state. So I thought a short blog post answering that question might be helpful. The following demo shows a div moving from left: 25px; to left: 300px;. Once it’s complete, it returns to its initial state.

Update 2015-05-21
Chrome 43 now lets you use CSS animations without the -webkit prefix.

Demo

HTML

<div class="movingbox"></div>

CSS

.movingbox {
    position: absolute;
    top: 25px;
    left: 25px;
    width: 50px;
    height: 50px;
    background: #222;
    border-radius: 5px;
    -webkit-animation: move 5s ease-in-out; 
            animation: move 5s ease-in-out;
}

@-webkit-keyframes move {
    100% {
        left: 300px;
    }
}

@keyframes move {
    100% {
        left: 300px;
    }
}

Now, let’s say that we want the animation to stop at 100%, persisting the div at left: 300px;, how would we do?

Easy, just add animation-fill-mode: forwards; and the final property defined in the last keyframe rule will be maintained.

In this case, like this:

-webkit-animation: move 5s ease-in-out forwards;
        animation: move 5s ease-in-out forwards;

Here’s an updated demo.

And that’s it, hope this helped!

One Reply to “How to maintain the end state in a CSS Animation”

Leave a Reply

Your email address will not be published.