The Five-Minute Guide to CSS Animations

Published on by Sara Allison RSS

by Peter Gasston

The Developer Preview of Internet Explorer 10 introduces support for CSS Animations, a fairly recent addition to CSS3 which allows you to animate the properties of an element, with some degree of complexity, and without the use of JavaScript.

In this article I’m going to race through the basics of CSS Animations, teaching you enough to get started in about five minutes worth of reading. If you’re already familiar with CSS Transitions then this should be really easy for you; CSS Animations are essentially just a series of transitions, and use much of the same terminology.

To view the examples in this article you’ll need to have a browser which supports them; that is IE10 Developer Preview, Chrome, Firefox, or Safari.

Before we get to any code, however, I’ll quickly introduce the concept of key frames. If you already know what these are – perhaps you know the fundamentals of animation, or you’re used to using Flash – you can skip this section.

Animation Key Frames

To put it simply, a key frame is a start or end point in an animation sequence. If you want to have a character walk across the screen from left to right, the first key frame would show them on the left and the second key frame would show them on the right. The movement between those frames is known variously as an inbetween, tween, or interpolation, but in CSS we call it a transition.

spacer

CSS Key Frames

You define your key frames in CSS by using the @keyframes at-rule, and each at-rule is assigned a unique identifier, like so:

@keyframes foobar {}

N.B. As Animations are still an experimental feature, you’ll have to use a prefix for each of the different browsers (-ms-, -moz-, and -webkit-) – for example, in IE10 you’ll need to use @-ms-keyframes.  This also applies to all of the properties I’ll be using in this article, although for clarity I’ll leave them out of my example code. But view the source of my demo pages if you’re not sure what the prefixed properties look like.

Your minimum number of key frames should be two – your start and end frames – and you define them inside the @keyframes rule:

@keyframes foobar {
from { left: 0; }
to { left: 100px; }
}

In this rule, which I’ve given the unique identifier foobar, the element I apply the rule to will move 100px from the left. You can see an example of this in Example 1; don’t worry about the code at the moment, it’s just to demonstrate the effect.

If I want a more complicated animation I can add more frames by specifying their position in the animation as a percentage:

@keyframes foobar {
from { left: 0; }
50% { color: #F00; left: 50px; }
to { left: 100px; }
}

In this updated rule my element will again move from left to right, but this time it will transition from the default colour to red on its way to the halfway point, then transition back to the default on its way to the end. You can see this in Example 2 – but again, it’s the effect you’re looking at, not the code.

Applying Animations

Now that we have our animation set up, how do we apply it? Very simply, we use the animation property. As I mentioned before, this is very similar to the transition property, so if you’re familiar with that then there’s nothing here to scare you.

Here’s the animation property with a full set of values:

e { animation: foobar 1s 500ms ease-out 10 alternate; }

Let me quickly run through each of those values in order. The first, foobar, is the unique identifier we created for the @keyframes rule. The next two values, 1s and 500ms, are time values (in seconds (s) or milliseconds (ms)) which set the time the animation will take to execute and the delay before it begins – if you use only one of these values it will be considered to be the time, and if you use both then the delay is always the second one provided.

The fourth value controls how smoothly the animation will execute; ease-out means the animation will slow down towards the end. The number after this, 10, is the number of times the animation will play – the default is 1. And finally, the alternate value means the animation will play from start to finish, then reverse order and play backwards; you could also use the value normal which will loop the animation back to the start each time it finishes playing.

The animation property is actually a shorthand; the properties it summarises are (in the same order I’ve used them above): animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, and animation-direction. Most of them are fairly simple and pretty much explained above, but animation-timing-function deserves a little more explanation (if you’re familiar with CSS Transitions you can skip this).

animation-timing-function

This property allows you a little more control over the way your animation plays through. If you want it to play at a uniform speed from start to finish, set this value to linear. If you want it to start off slowly at first then accelerate to a uniform speed until the end, use ease-in; and if you want the opposite, use ease-out. There’s also the ease-in-out value, which starts and ends slowly with a linear transition between. The default value is ease, which is similar to ease-in-out but with slightly more pronounced speed differences.

If you need more fine control over your transition speeds, you can use the cubic-bezier() function instead of one of these keywords. It would take me more than the length of this article to explain cubic Bézier curves, so instead I strongly suggest you look at the timing function page on MDN, which explains what they are and how each of the keyword values relate to them. If you do want to make your own transitions, I highly recommend this tool for creating custom curves by Lea Verou.

The other value you can use for animation-timing-function is the steps() function. This plays the animation through in a series of stages rather than one smooth curve; for example, I could play my animation through in six steps by using this:

e { animation-timing-function: steps(6); }

This is very useful for animating image sprites, as you can see in this sprite sheet animation demo by Simurai.

Your Five Minutes Are Up

In Example 3 I’ve put together a more complex animation using some of what we’ve learned; in this case I do want you to take a look at the code so that you can see what I’ve done. Although I haven’t used all of the properties introduced in this article, there should be enough there for you to realise the power that’s available to you when using CSS Animations.

If you want to make your own animations the information I’ve given you above should be enough to get you started. If you want to get a bit more in-depth, however, read on to find out about some other properties I haven’t introduced yet, and how to combine CSS Animations with JavaScript events.

Other Animation Properties

There are a couple more animation properties you may find useful. animation-fill-mode is the first, and this is used to set the way the element displays before and after the animation has run. Without this there may be a quite abrupt movement between the element’s default state and its animated state. Its default value is none, which means the element will appear in its default state, but you could also choose forwards, which will make the element appear as it does in the to (or 100%) keyframe, backwards, which makes it appear as in the from or (0%) keyframe, or both, which will display like the from keyframe at the beginning and the to keyframe at the end.

The second property is animation-play-state, which sets whether the animation is running or paused, and so accepts a value of either running or paused (obviously). So if you want to pause your animation on mouse hover you’d use this:

e:hover { animation-play-state: paused; }

Note that there’s an ongoing discussion as to whether or not this property will be in the final release of the Animations specification, as you can replicate the same functionality by other means.

JavaScript Events

CSS Animations are pretty powerful on their own, but they really come into their element when you combine them with JavaScript, allowing you to chain them together and add or remove animations to elements as required. There are three JavaScript events that get fired during each animation:

animationstart is fired when the animation begins for the first time.

animationiteration fires when the animation begins, and each time it plays through (based on the animation-iteration-count property).

animationend is fired when the animation completes its final iteration – so if the count is infinite, it will never fire.

I’m sure you can see how these could be useful. You could, for example, have two animations (called foo and bar, for originality):

.foo { animation: foo 1s; }
.bar { animation: bar 1s; }

And apply the second to the target element only when the first has completed, by creating a JavaScript function somewhat like this:

var foo = document.querySelector(‘.foo’);
foo.addEventListener(‘animationend’,function(e) {
e.currentTarget.className = ‘bar’;
});


Further Reading

  • Hands On: Animations – Very useful live preview tool, letting you see the effect that changes to different values have on your animations.
  • Introduction to CSS3 Animations – David Rousset has written this very in-depth introduction, which delves further into things I didn’t have space to cover here, like fallback options for non-supporting browsers.
  • CSS Animations on MSDN – This is like a user manual, explaining in detail all of the properties and related functions and events, with examples.
  • The Book of CSS3 – My book contains much more detail about CSS Animations, and the supporting website has examples for you to view.
_________________________________________________________________________________________

spacer Peter Gasston has over ten years experience in front end development in both agency and corporate environments, working for and with some of Britain’s biggest media companies, and is currently the senior front-end developer at Top10.com. Peter is a public speaker, the author of The Book Of CSS3, and writes the well-respected blog about web technologies, Broken Links.

Tweet this post

Published by Sara Allison

spacer

Sara is the editor of Ubelly - when not heads down scouring Ubelly articles for typos (and not always catching them), she's scouting for new writing talent. Give her a shout @SaraAllison if you've got something to say about development/design and want to be heard.

One Comment So Far, what do you think?

  1. Pingback:My Happy New Year - Broken Links

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a class="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

spacer