CSS3 Keyframes

This is a post from my original Wordpress blog. It has some valuable information so I decided to reinstate some of these old posts. Originally posted on September 14, 2010.

There are two main options for using CSS3 animations: keyframes and transitions. Both have their advantages and are syntactically different. I'll do my best to explain each in Layman's terms and also give some examples. In this post I'll be going over keyframes.

Keyframes let you control what properties are changed and when. To create a keyframe animation, you need the following:

Here is an example:

@-webkit-keyframes move {
    from {
        left: 0px;
    }
    to {
        left: 200px;
    }
}

Optionally, if you use 0% - 100%, you can also provide steps of changes in between. You chose the percentages of the steps. I usually match up the percentages with my timing. If my animation is going to take 4 seconds and I want the color to change at 1.5 seconds, then I just do 1.5/4*100 = 37.5%. So, my new keyframe will look like this:

@-webkit-keyframes move {
    0% {
        left: 0px;
        background:red;
    }
        38% {
        background:blue;
    }
        100% {
        left: 200px;
    }
}

Now that you have defined your animation, in this case we've called it "move", we can apply it to a DOM object. Personally, I always store my animations in their own separate classes. This does not mean that you cannot store the animation and it's properties in a main class, ID, or even in the DOM CSS definition (ie. div, a, img), I think it's just better practice to keep them separate. Here are all of your animation options:

Keyframes are a great way to keep messy and resource using Javascript off of your pages and away from your users. But, keep in mind that only browsers using the Webkit engine will be able to utilize them. Currently, this means only Chrome and Safari. However, both Mozilla and Opera will be using animations very soon. I believe Firefox 3.7 will be using -moz and Opera may already support some -o animations.

Another downside, and the reason I stick mostly to transitions, is that mobile support for keyframes is pretty weak. Yes, you will your iPhone to render a keyframe animation, but it will be just as choppy as a jQuery.animate({...}) function.

In the next CSS Animations post, I'll be covering -webkit-transitions, and after that I'll be showing some examples of how to tie it all together and create some amazing works/tools with some help from Javascript.

I left out any examples of how to use keyframes in this post, but be sure to check out some of the sources I used to create this small guide for some excellent examples and source code: