Animation

Animating Objects with CSS

Animation is a technique of creating the illusion of movement by displaying a sequence of changing images, known as key frames, in rapid succession. The brain interprets the rapidly changing key frames not as distinct images but rather as a single image in motion. CSS replaces the concept of key frame images with key frame styles that are applied in rapid succession to a page object. While a transition is limited to two style rules defined at the initial and end states, an animation can contain multiple styles defined for each key frame.

 The @keyframes Rule

To define a sequence of key frames in CSS, apply the following @keyframes rule

    @keyframes name {
        keyframe1 {styles;}
        keyframe2 {styles;}
       ...
    }

where name provides the name or title of the animated sequence, keyframe1, keyframe2, and so on defines the progress of individual key frames, and styles are the styles applied within each key frame. The keyframe1, keyframe2, and so on values are expressed as percentages where 0% indicates a key frame at the start of the sequence and 100% represents the sequence’s last frame. The 0% and 100% values can also be replaced with the keywords from and to. At the time of this writing, some browsers require a browser extension to define the key frames. For example, if you are using Safari, you might have to add the following WebKit extension to your code:

    @-webkit-keyframes name {
        keyframe1 {styles;}
        keyframe2 {styles;}
    }

Check with your browser documentation to determine its level of support for CSS3 key frames.

Key frames can be used to move objects across the page as in the following @keyframes rule that traces out an object’s flight path (see Figure 8-43).

    @keyframes flight {
    from {left: 0px; top: 0px;}
    5%	{left: 50px; top: 80px;}
    10% {left: 70px; top: 80px;}
    20% {left: 90px; top: 25px;}
    to	{left: 60px; top: 10px;}
}