CSS Animation Tips and Tricks

CSS Animation Tips and Tricks

This post will take 2 minutes to read.

CSS animations are becoming quite popular thanks to things like Animate.css and Animatable. I have been using them quite a bit recently and decided to compile a list of tips for those that haven’t spent that much time with them. Here are the things I will be discussing:

  1. Using multiple animations.
  2. Running sequential animations.
  3. Using animation-fill-mode on delayed animations.
  4. Stopping your animations from flickering.
  5. Controlling the play state of your animations.

For those that aren’t familiar with the animation syntax please check out Chris Coyier’s neat write up.

Keep in mind that for now all browser prefixes will need to be used (webkit, moz, ms and o).

Use multiple animations

This one is pretty straightforward: you may list several animations and have them all run together. You would do so like this:

animation: fadeIn 1s ease-in,
           rotate 2s linear 2 alternate;

Details on the animation shorthand property can be found here.

Run sequential animations

But what if you didn’t want both of the above animations to start at the same time? What if you wanted the first animation to complete before the second began? This is achievable by setting a delay on the second animation equal to the duration of the first animation:

animation: fadeIn 1s ease-in,
           rotate 2s linear 1s 2 alternate;

Use animation-fill-mode on delayed animations

This one is a little trickier to explain but let’s say that you had the following:

div {
    animation: fadeIn 1s ease-in,
               rotate 2s linear 1s 2 alternate;
}
@keyframes fadeIn {
    0% { opacity: 0; }
    100% { opacity: 1; }
}
@keyframes rotate {
    0% { -webkit-transform: rotate(45deg); }
    100% { -webkit-transform: rotate(0deg); }
}

That code won’t work as well as you might think (see here): the first animation will run, and then, as the second animation starts, the div will instantly rotate 45 degrees. You can combat this by using the animation-fill-mode property.

div {
   animation: fadeIn 1s ease-in,
              rotate 2s linear 1s 2 alternate both;
}

Basically, defining a fill-mode will display the animation’s first/last keyframe before/after the animation runs. More information can be found here.

Stop your animations from flickering

This is a nifty little trick I found while troubleshooting a problem. Here is the write up.

Control the play state of your animations

I haven’t actually found a use for this last tip yet but I’m hoping I will shortly. Put simply, the animation-play-state defines whether an animation is running or paused. As far as I am aware, you cannot include this property in the animation shorthand. Here is an example of how it works.

Tweet this