CSS Animation Tips and Tricks

CSS Animation Tips and Tricks

This post will take 2 minutes to read.

CSS anim­a­tions are becom­ing quite pop­u­lar thanks to things like Animate.css and Animatable. I have been using them quite a bit recently and decided to com­pile 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 mul­tiple animations.
  2. Running sequen­tial animations.
  3. Using anim­a­tion-fill-mode on delayed animations.
  4. Stopping your anim­a­tions from flickering.
  5. Controlling the play state of your animations.

For those that aren’t famil­i­ar with the animation syn­tax please check out Chris Coyier’s neat write up.

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

Use multiple animations

This one is pretty straight­for­ward: you may list sev­er­al anim­a­tions and have them all run togeth­er. You would do so like this:

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

Details on the anim­a­tion short­hand prop­erty can be found here.

Run sequential animations

But what if you did­n’t want both of the above anim­a­tions to start at the same time? What if you wanted the first anim­a­tion to com­plete before the second began? This is achiev­able by set­ting a delay on the second anim­a­tion equal to the dur­a­tion 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 trick­i­er 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 anim­a­tion will run, and then, as the second anim­a­tion starts, the div will instantly rotate 45 degrees. You can com­bat this by using the animation-fill-mode property. 

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

Basically, defin­ing a fill-mode will dis­play the anim­a­tion’s first/last key­frame before/after the anim­a­tion runs. More inform­a­tion can be found here.

Stop your animations from flickering

This is a nifty little trick I found while troubleshoot­ing a prob­lem. Here is the write up.

Control the play state of your animations

I haven’t actu­ally found a use for this last tip yet but I’m hop­ing I will shortly. Put simply, the animation-play-state defines wheth­er an anim­a­tion is run­ning or paused. As far as I am aware, you can­not include this prop­erty in the animation short­hand. Here is an example of how it works.

Tweet this