csscss-transitionscss-animations

CSS: Animation vs. Transition


I understand how to perform both CSS3 transitions and animations. What is not clear is when to use which.

For example, if I want to make a ball bounce, it is clear that animation is the way to go. I could provide keyframes and the browser would do the intermediates frames and I'll have a nice animation going.

However, there are cases when a said effect can be achieved either way. A simple and common example would be implement the Facebook style sliding drawer menu:

This effect can be achieved through transitions like so:

.sf-page {
    transition: transform .2s ease-out;
}

.sf-page.out {
    transform: translateX(240px);
}

http://jsfiddle.net/NwEGz/

Or, through animations like so:

.sf-page {
    animation-duration: .4s;
    transition-timing-function: ease-out;
}

.sf-page.in {
    animation-name: sf-slidein;
    transform: translate3d(0, 0, 0);
}

.sf-page.out {
    animation-name: sf-slideout;
    transform: translateX(240px);
}

@keyframes sf-slideout {
    from { transform: translate3d(0, 0, 0); }
    to { transform: translate3d(240px, 0, 0); }
}
 
@keyframes sf-slidein {
    from { transform: translate3d(240px, 0, 0); }
    to { transform: translate3d(0, 0, 0); }
}

http://jsfiddle.net/4Z5Mr/

With HTML that looks like so:

<div class="sf-container">
    <div class="sf-page in" id="content-container">
        <button type="button">Click Me</button>
    </div>
    <div class="sf-drawer">
    </div>
</div>

And, this accompanying jQuery:

$("#content-container").click(function(){
    $("#content-container").toggleClass("out");
    // below is only required for css animation route
    $("#content-container").toggleClass("in");
});

What I'd like to understand is what are the pros and cons of these approaches.

  1. One obvious difference is that animating takes a whole lot more code.
  2. Animation gives better flexibility. I can have different animation for sliding out and in.
  3. Is there something that can be said about performance. Do both take advantage of hardware acceleration?
  4. Which is more modern and the way going forward?

Solution

  • It looks like you've got a handle on how to do them, just not when to do them.

    A transition is an animation, just one that is performed between two distinct states - i.e. a start state and an end state. Like a drawer menu, the start state could be open and the end state could be closed, or vice versa.

    If you want to perform something that does not specifically involve a start state and an end state, or you need more fine-grained control over the keyframes in a transition, then you've got to use an animation.