Animations on the Web

Forget about Flash and GIFs (which I stubbornly continue to pronounce GIFs as opposed to JIFs) -- CSS animations are the future!

Well, present (and the future), really; they are already being used quite regurarely. See that little rocket, just zooming around? Yes, that's CSS. Interested in learning how it works -- and perhaps making your own CSS-animated space vehicles? Well, prepare for a quick crash course with...

A
Gentle introduction
to

CSS3 Animations

by @fourtonfish

Getting ready

Wasn't that nice? Anyway, if you want to follow along -- which you should, it will be more fun that way -- open up a new Thimble. Now, paste the following code after </title>:

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css" rel="stylesheet">

What this piece of code does is that it loads the Font Awesome icon font. We will use this for our little animations.

What is CSS?

You probably alreday know what CSS is -- it's the language you use to make your HTML look pretty. It lets you change color, fonts, padding and many other things. Let's try something now: put the following code inside your <body>:

<i class="fa fa-heart"></i>

What is CSS?

Yep, it's a heart.

Now try doing this: go back to your <head> section of the code and add:

<style>
  #heart{
    color: YOUR_FAVORITE_COLOR_HERE (for example red);
  }
</style>

What is CSS?

Wait, it's still the same heart as before!

Of course, we used a CSS selector that modifies the style of an element with the id heart. We need to do a little change to our code:

<i id="heart" class="fa fa-heart"></i>

There, see the difference?

What is CSS?

Now, you might be wondering: why didn't we simply change the style of the fa-heart class? The answer is simple: what if you wanted to have two hearts on your page, red and blue? It makes more sense to have either separate IDs or classes for each element.

Anyway, let's add this little snippet between our <style> tags to make our page look a bit nicer:

body{
  text-align: center;
  font-size: 4em;
  padding: 3em;
}

Animating with CSS

Now for the fun part. There are basically two ways of using CSS for animation:

Let's get into what these mean.

CSS3 Transitions

Let's update our #heart's CSS again:

#heart{
  color: red;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -o-transition: all 1s;
  transition: all 1s;
}

And right after this, let's add:

#heart:hover{
  color: blue;
}

CSS3 Transitions

Now try hovering over the heart.

Let's break down the code we just wrote:

transition: all 1s;

transition tells the browser that we want to animate certain properties -- in our case all of them. And the animation should take 1 second (1s).

#heart:hover{
  color: blue;
}

Then we changed the color of our #heart element when we hover over it. Without the transition, the color would simply change abruptly: go ahead and try to remove the transition code.

Since we told the browser how and what we want to animate, it followed our instructions and we saw the color property change with a one second animation.

Pretty neat.

Also note that we added vendor prefixes (for example -moz-) to support older browsers.

CSS3 Transitions

To get a little more technical, the actual code looks like this:

#heart{
  transition-property: all;
  transition-duration: 1s;
}

but instead of writing all the transition properties, you can simply write transition and write the values you want to use. Here's the full list of properties for reference:

#heart{
  transition-property: all;
  transition-duration: 1s;
  transition-delay: 2s;
  transition-timing-function: linear;
}

Let's see what values we can use for each property.

CSS3 Transitions

Let's start with the example code from previous slide:

#heart{
  color: red;
  transition-property: all;
  transition-duration: 1s;
  transition-delay: 2s;
  transition-timing-function: linear;
}

Because of the transition-delay property set to 2 seconds (2s), you need to hover the heart for two seconds before the animation kicks in.

What about the transition-timing-function? Let's find out.

CSS3 Transforms

CSS3 Transitions can animate a variety of properties related to position, color or borders. See this useful page under Animatable properties for a list of properties you can animate.

The transform property is also often used for animation and it lets you apply 2D and 3D transformations, such as skew, zoom or rotate3d. You can find a full list of possible transformations here.

Let's change the CSS for our #heart when it's hovered over.

#heart:hover{
  transform:scale(1.3);
}

And for our #heart:

#heart{
  color: red;
  -webkit-transition: all 1s cubic-bezier(.66,-0.48,.41,1.76);
  -moz-transition: all 1s cubic-bezier(.66,-0.48,.41,1.76);
  -o-transition: all 1s cubic-bezier(.66,-0.48,.41,1.76);
  transition: all 1s cubic-bezier(.66,-0.48,.41,1.76);
}

Now this is a bit more advanced, but you should at least get the idea: the timing function lets you control the speed curve of the animation. The options here are:

And if you want to be technical, you can, of course, also use initial (the default value) and inherit (which will inherit the value from the parent element). Try changing the values for the timing function to each of these to see how they differ. You may also want to set the duration of your animation to something other than 1s to see the effect better.

cubic-bezier is the most powerful value -- actually a function -- that lets you achieve some really cool effects. In our example we made the heart go in a little bit before growing bigger and it also goes a little bit out and back in as the animation ends. There is a nice little online tool that lets you generate bezier curves -- go ahead and try animating your heart with different curves.

CSS3 Animations

CSS3 Animations give you more freedom over the effects you apply. Let's try something simple:

@keyframes beat{
  0%{
    transform: scale(1)
  }
  50%{
    transform: scale(2)
  }
  100%{
    transform: scale(1)
  }
}

#heart:hover{
  animation: beat 4s infinite ease;
}

With @keyframes you are telling the browser what effects should be applied during specific points of the animation. Here we are saying: I want the scale of the element to be 1 when the animation starts, then I want the element to double in size (scale(2)) when the animation is halfway through (50%) and when the animation ends, I want the element to be back to its original size.

And with animation: beat 4s infinite ease; we are asking the browser to use the animation we created with a 4s length (so the 50% refers to the animation at a 2 second time mark) and we want it to loop infinitely and at a constant speed (using ease as the timing function).

CSS + JavaScript

Now all of this is nice when you want to apply animation when you hover a cursor over an element. What if you want to animate an element when something happens on your website?

The solution is simple: instead of element:hover you will define a new class, for example element-animated and add this class to your element with JavaScript. Let's see how this works.

CSS + JavaScript

You can click all you want, nothing will happen on this page.

CSS + JavaScript

Let's first add a few elements to our page:

<button id="animate"><i class="fa fa-magic"></i> <span id="animate-title">Animate!</span></button>
<p><i id="refresh" class="fa fa-refresh"></i></p>
<p><i id="cloud" class="fa fa-cloud"></i></p>
<p><i id="plane" class="fa fa-plane"></i></p>

Great. Now we need to decide how we want to animate our little elements. Go ahead and make your own animations, I am going to go with something like this:

@keyframes startrefresh{
  from{
    transform: rotate(0deg)
  }
  to{
    transform: rotate(720deg)
  }
}

.refreshing{
  animation: startrefresh 2s infinite ease;
}   

CSS + JavaScript

Next, we will add the following JavaScript code before our closing </body> tag:

<script>
  document.addEventListener('DOMContentLoaded', function(){
    var animationOn = false;
    document.getElementById("animate").addEventListener("click", function(){
      if (animationOn === false){
        animationOn = true;
        document.getElementById("animate-title").innerHTML = "Pause! (And bring back the cloud)";
        document.getElementById("refresh").classList.add("refreshing");
        document.getElementById("refresh").classList.remove("refreshing-pause");        
      }
        else{
          animationOn = false;
          document.getElementById("animate-title").innerHTML = "Resume!";
          document.getElementById("refresh").classList.remove("refreshing");
          document.getElementById("refresh").classList.add("refreshing-pause");       
        }
      });
  });
</script>

Here we are asking the browser to wait until the content of the page is loaded and add a function that:

You can try adding your own animation to the other elements.

CSS + JavaScript

And that's really it! Feel free to play with all the available properties and their values and come up with some creative effects. Here are some more examples:

Fin

I hope you enjoyed this little overview of CSS3 Animations. If you have any questions or suggestions for this tutorial, send me an email or find me on Twitter.

Thanks and have a great day!

PS: See the next slide for additional resources.

Additional resources

Bonus activities (Remix)

For some examples of what can be done using only CSS3 animations (without any JavaScript) be sure to check out this elaborate 3D scene with moving cars and this little web app :)