kirupa.com - Creating a Simple CSS Animation 


Active Discussions

Creating a Simple CSS Animation

by kirupa   |   13 August 2011

  Have questions? Discuss this HTML5 tutorial with others on the forums.

One of the major features introduced with CSS3 is the ability to define animations. Using just a few lines of simple markup, you can create some really elaborate transitions involving multiple keyframes, easing functions, and more!

In this tutorial, you will learn the basics of how to create CSS animations, and below is an example of the animation that you will create:

[ click here for a live / running example ]

You can see a live example here if you are running on a recent version of Firefox, Chrome, Opera, or Safari. Internet Explorer 9 doesn't support CSS3 animations, but Internet Explorer 10 should.

With the obligatory disclaimer about browser support out of the way, let's get started!

Getting Started

What we are going to do is take a simple example and add the appropriate CSS magic needed to create an animation.

First, create a new HTML document with the following HTML and CSS as its content:

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>CSS3 Animation Example</title>
<style>
#mainContent {
font-family: Arial, Helvetica, sans-serif;
font-size: xx-large;
font-weight: bold;
background-color: #B1DBFC;
border-radius: 4px;
padding: 10px;
width: 350px;
height: 200px;
overflow: hidden;
}
#myImage {
width: 100px;
height: 100px;
position: relative;
left: -150px;
padding-top: 50px;
}
</style>
</head>
<body>
<div id="mainContent">
<img id="myImage" alt="arrow that will be animated" src="http://www.kirupa.com/images/blueArrow.png"></div>
</body>
</html>

If you preview this page in your browser, you will see is the following:

a blue rounded rectangle

[ a blue rounded rectangle and an image...yay! ]

This is a good starting point. What we are going to do is animate that image from the left side of your blue container to the right side using nothing but CSS.

Adding a CSS Animation

There are two parts to a CSS animation:

  1. Specifying the various properties your animation will have.
     
  2. Defining the keyframes that will actually bring your animation to life.

Let's first add the animation properties to the CSS that will be affecting our image. We already have a rule defined for our image, and that is the one with the selector myImage:

#myImage {
width: 100px;
height: 100px;
position: relative;
left: -150px;
padding-top: 50px;
}

What we are going to do is add the animation-related CSS properties here. Go ahead and modify your myImage rule by adding the following CSS properties:

#myImage {
-moz-animation-name: imageSlide;
-moz-animation-duration: 2s;
-moz-animation-timing-function: ease-in;
-moz-animation-iteration-count: infinite;
-webkit-animation-name: imageSlide;
-webkit-animation-duration: 2s;
-webkit-animation-timing-function: ease-in;
-webkit-animation-iteration-count: infinite;
-ms-animation-name: imageSlide;
-ms-animation-duration: 2s;
-ms-animation-timing-function: ease-in;
-ms-animation-iteration-count: infinite;
width: 100px;
height: 100px;
position: relative;
left: -150px;
padding-top: 50px;
}

If you made these changes and previewed your animation, you won't see anything different from what you saw earlier. The reason is that these properties only define the animation and set some properties on it like how long it will take to run, what kind of easing function to use, and how many times to loop, etc. These properties don't actually specify the property changes necessary to visualize our animation.

The changes that help you visualize your animation are defined inside keyframes. Let's go ahead and add them. Copy and paste the following @keyframes rule inside your style region (outside of the myImage rule):

@-moz-keyframes imageSlide {
0% {
left: -150px;
}
20% {
left: 50px;
}
80% {
left: 200px;
}
100% {
left: 600px;
}
}
@-webkit-keyframes imageSlide {
0% {
left: -150px;
}
20% {
left: 50px;
}
80% {
left: 200px;
}
100% {
left: 600px;
}
}
@-ms-keyframes imageSlide {
0% {
left: -150px;
}
20% {
left: 50px;
}
80% {
left: 200px;
}
100% {
left: 600px;
}
}

Once you have added these keyframes, preview your HTML page. This time, because you added your keyframes, you will see your blue arrow image scrolling from left to right.

If you aren't seeing the image scrolling, and you are testing in Firefox, Chrome, or Safari, make sure everything in your source looks the same as what you see in the live example.

How CSS Animations Work

You now have a working example where you are using CSS to animate an image in your document. All that is left is to figure out why the code you added ends up creating the animation that you see. But...before we look at the code, let's first explore how CSS animations work.

Animations in CSS work by creating a transition between property changes over a period of time. Let’s look at this visually in the context of the arrow image we are animating in this tutorial.

Our sliding animation starts with our image located on the left side of the screen:

starting position

In the end, our image is located on the right side:

end position

What we call our animation is the changing of our image's left CSS property between our starting and ending points over a period of time. If we just interpolate the value of the left property between the starting and ending points, your arrow will look like the following:

interpolated positions of the arrow image

Let's throw an important concept into the mix - the duration. Your animation's duration determines how long it runs before it completes. A small duration means that your animation runs very quickly, and a large duration means your animation is pretty slow.

For this example, let’s say that our animation has a duration that is 2 seconds:

the duration makes an appearance

This means it will take our arrow image two seconds to get from the left hand side to the right hand side. That's pretty simple, right?

Let's kick this animation up a few notches. Despite this tutorial's title, we aren't creating that simple of an animation. In CSS, you have the ability to define more than your animation's starting and ending points. You actually have the ability to define intermediate points that give you greater control over what properties get affected as your animation is rolling.

These intermediate points are more formally known as keyframes. For starters, let's define our starting and ending keyframes:

keyframes

Notice the two keyframe are labeled as 0% and 100%. The reason is that keyframes in CSS3 are not designated by frame numbers, but instead, they are designated by percentages.

The percentage determines when in the lifetime of your animation that keyframe will become active. This is done by multiplying the percentage by the duration to figure out the exact second that keyframe should become active.

Calculating when our starting and ending keyframes become active is pretty easy. The 0% keyframe corresponds to the 0 second or starting point of our animation. The 100% keyframe corresponds to the 2 second or ending point of our animation.

The real fun happens when you define additional keyframes in-between your start and end. For example, if I want to alter the rate at which my image's left property is changing, I can insert some keyframes at the 20% and 80% points and alter the left property's value accordingly:

keyframes are here!

To clarify, unlike other animation systems you may be familiar with, Inserting new keyframes does not alter the overall duration of the animation. The only thing that gets altered is what your animation does when a particular keyframe becomes active. Because our duration is still 2 seconds, the 20% keyframe will become active at the .4 second mark. Similarly, the 80% keyframe will become active at the 1.6 second mark. The overall duration of the animation still remains constant at 2 seconds!

Phew!

Deconstructing our CSS

In the previous section, you received a high-level overview of how CSS animations work. In this section, let's get more concrete and see how what you learned earlier translates into a working animation.

To reiterate, a CSS animation is made up of two parts:

  1. Specifying the various properties your animation will have.
     
  2. Defining the keyframes that will actually bring your animation to life.

Let's look at the code for these two parts in greater detail.

Specifying the Animation Properties

To help define and setup your animation, you have the animation properties that...as you can guess, begin with the keyword animation. These properties tell your browser what your animation is actually called, how long your animation will run, and so on; and these properties live on the CSS rule the element or elements you wish to animate are associated with.

In our case, jump to your myImage rule and find the animation properties that you added earlier. If you ignore the vendor prefixes for a moment, the animation properties will look as follows:

animation-name: imageSlide;
animation-duration: 2s;
animation-timing-function: ease-in;
animation-iteration-count: infinite;

Let's look at each of these properties in greater detail.


Up first is our animation-name property:

animation-name: imageSlide;

The animation-name property, as its name implies, allows you to specify your animation's name. As you will see shortly, this name isn't just for your own benefit. When we look at how keyframes are defined, you will see this imageSlide animation playing an integral role.


Next up is the animation-duration property:

animation-duration: 2s;

This property is pretty simple in what it defines. It allows you to specify how long your animation will take to complete. In our case, our animation will take 2 seconds to run to completion. See, told you it was simple!


The next property specifies the easing function you can use to alter the rate of the property changes:

animation-timing-function: ease-in;

By default, the interpolation of the property values between keyframes is linear. You can alter that by specifying an easing function using the animation-timing-function property. The values you can use are:

Explaining these easing functions in greater detail goes beyond the scope of this tutorial, so you should play with these values to see how your choice of easing function changes what your animation does.


The last property that we use to setup our animation is:

animation-iteration-count: infinite;

The animation-iteration-count property specifies how many times our animation will loop. In our example, we use the keyword infinite to let our animation know it needs to keep playing forever. If you don't want your animation to play till the end of time, you can always specify a number.

With that, we have looked at one-half of what makes up a CSS animation. Let's look at the other half that involves keyframes next.

The Keyframes

The real magic happens in the keyframes where the properties that need to change as our animation plays are defined. To help explain the keyframes, let me provide an image that I used earlier:

keyframes are here!

Keep this image in mind as you are looking at the keyframes at-rule below:

@keyframes imageSlide {
0% {
left: -150px;
}
20% {
left: 50px;
}
80% {
left: 200px;
}
100% {
left: 600px;
}
}

Deconstructing our keyframes is pretty straightforward. First, you have our at-rule called keyframes followed by your animation name:

@keyframes imageSlide {

Our animation name is imageSlide. Pause for a moment. Doesn't that name look familiar?

As you saw earlier, you specified this name when setting the animation-property inside your myImage rule. The names being identical is what links the animation properties you defined earlier with the keyframes associated with it here. If the names didn't match up, then these keyframes wouldn't know what to actually affect.


The actual keyframes themselves can be seen below:

0% {
left: -150px;
}
20% {
left: 50px;
}
80% {
left: 200px;
}
100% {
left: 600px;
}

As you can see, there are four keyframes - 0%, 20%, 80%, and 100%. Inside each keyframe are the properties and the values we want those properties to have.

In our case, because we are just sliding our image from one side to the other, the only property we are changing is the left property. The values of the left property at each keyframe are designed to give you the effect of having the image slide in really fast, slow down a bit, and then slide out really quickly.

When you put all of this together, namely with our 2 second duration and ease-in easing function, you have an animation where your left property smoothly transitions from -150 pixels to 50 pixels in .4 seconds, 50 pixel to 200 pixels 1.2 seconds, and from 200 pixels to 600 pixels in .4 seconds. Because we have set our animation's animation-iteration-count property to be infinite, you can look forward to your image oscillating from -150 pixels to 600 pixels for many many years to come!

You should note that there is more to keyframes than what I have presented here. You can actually set certain animation properties inside the keyframe itself, and you can also use from and to instead of a percentage to define simple transitions. These topics will be described in greater in the future.

Conclusion
Well, there you have it! In this big bite-size tutorial, you learned how to add a CSS Animation to a simple document, what makes these animations work, and how the various tags and properties work together to create change you can see.

By no means is this tutorial comprehensive. There are many other facets of CSS animations that I didn't have room to cover in this tutorial, but stay tuned for future tutorials!

Need Help?

If you have questions, need some assistance on this topic, or just want to chat - please drop by our friendly forums and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out. Plus, we have a large collection of smileys you can use

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Kirupa Chinnathambi
about | facebook | twitter


cloud storage
                          EdgeCast CDN
kirupa.com's fast and reliable hosting provided by Media Temple. Creative web apps. Make your own free flash banners and photo slideshows.
HTML5 CSS3 Mobile Gallery for iPhone, iPad Flash effects. Art without coding.
Flipping Book - page flip flash component. Flash-Gallery.com - Get your flash photo gallery (flash component or swf gallery
Learn how to advertise on kirupa.com