Loading...

To get an animation up and running, we need a new at-rule and some new properties.

Animations in CSS come in two main pieces. One piece is setting the directions for the animation, and the other is telling the target element it is going to perform the animation. First, let's set up directions for a basic animation. To do that, we need to use the @keyframes at-rule.

Like other at-rules, @keyframes is placed in a style sheet. The first thing you need to do is name this direction set, so that we can call on it later. So for this demonstration, we'll just name it myAnimation. An animation's name is just typed right after "@keyframes", separated by a space.

@keyframes myAnimation {

}

Now we can place the animation steps inside the curly braces. For this introductory animation, we'll use the keywords from and to, which establish the start and end states of the animation, respectively. These keywords also get their own set of curly braces, in which we add the declarations we'd like to animate. So in this example below, we'll be changing the font color from light blue to black.

@keyframes myAnimation {
/* The animation will start with light blue font */
from { color: #CCCCFF; }
/* And will gradually change to black font */
to { color: #000000; }
}

All we have left to do is tell an element to perform the animation and for how long. These directions are added like any other styles. We will add the animation-name property to our element, and set its value to the animation name we chose: myAnimation. Then, using the animation-duration property, we can set how long we want the animation to take. The animation-duration property is required, because it is set to 0 by default, which would result in no animation.

Since animations usually start automatically, the example below has been set to repeat so you can see it in action. By default, animations only run once, but we'll learn how to change that later in the lesson.

<style>
@keyframes myAnimation {
from { color: #CCCCFF; }
to { color: #000000; }
}
div {
animation-name:myAnimation;
animation-duration:3s;
}
</style>
Color-changing text!