Pro CSS3 Animation

(Tuis.) #1

Chapter 5 ■ CSS3 Keyframe animationS


■ Note Smooth playback of animation sequences occurs if a new frame is shown approximately every

50 milliseconds, depending on the speed of motion on the screen. Keeping true to the principles of CSS, the animations

module does not attempt to define the playback rate or the number of frames shown per second (fpS). all CSS

animation is defined by states (to and from a state) or how long a sequence takes (time before and time after a

state). the rest is left up to the browser or client. you can absolutely optimize your CSS declarations to reduce the

load on the browser and create a more efficient animation, but you do not create your sequences “frame-by-frame”

(with the possible exception of step transitions, discussed in Chapter 3), and you cannot define a frame rate.

CSS3 Keyframe Animation Syntax


A keyframe animation always starts with an animation name which, as with an id value, must be unique. If two
keyframe sequences have the same name, only the last one will be recognized. The animation sequence itself
may be specified in two ways. The first of these is as a from ... to declaration, as shown in Listing 5-1.


Listing 5-1. Keyframes for a Simple Left-to-Right Animation


@keyframes slide {
from { left: 0; }
to {left: 100%; }
}


The animation can also be specified as percentage in time, shown in Listing 5-2.

Listing 5-2. Multiple Keyframes for a Complex Animation


@keyframes multislide {
0% { left: 20px; }
20% { right: 200px; }
80% { left: 50px; }
100% { right: 180px; }
}


If you do not explicitly define start or end states (from/0% or to/100%) in your animation declaration, the
browser will interpolate from or to the initial or final states of the element(s). You can also create a hybrid of
keywords and values in the declaration, as shown in Listing 5-3.


Listing 5-3. A Keyframe Sequence with a Mix of Keywords and Percentage Values


@keyframes multislide {
20% { right: 200px; }
80% { left: 50px; }
to { right: 180px; }
}


Because it only describes two states, the CSS Animation syntax shown in Listing 5-1 produces a result that
is essentially equivalent to a transition, although the animation method still retains several advantages over a
transition sequence, as you will see shortly.
Practically, the keyframe sequences can be written anywhere in your CSS, but I recommend that in most
cases you keep them at the top of your stylesheet, alongside any @font-face declarations, for easy reference.

Free download pdf