Pro CSS3 Animation

(Tuis.) #1

CHAPTER 2 ■ CSS3 TRAnSfoRmS And TRAnSiTionS


There is just one more improvement to make. You’ll notice that after the element has been rotated, moving
your mouse off the image returns it instantaneously to its initial state. While that may be the visual effect you seek
for web page elements in some circumstances, in most cases it is better to show the element returning to its initial
orientation just as smoothly as it arrived in its rotated state.
The solution is slightly counterintuitive: move the transition portion of the CSS code from the :hover
declaration to the default state for the image, keeping only the transform on the :hover declaration (see
Listing 2-14).


Listing 2-14. Creating a Smooth Transition to and from a Default State



The idea is simple: placing the transition property on the class declaration implies that any transition is
in effect both from and back to this state. The previous example placed the transition on the :hover declaration,
meaning that it was only effective on mouse hover, not during the return to the normal state.
You’ll also notice that the transition can be interrupted if you move your mouse to and from the area of the
image; its motion will be reversed smoothly. You can shortcut the code further by only specifying the time for the
transition (see Listing 2-15).


Listing 2-15. Timed Rotation in a CSS Transformation


img.tilt {
width: 300px; height: 300px; float: left;
-moz-transition: 2s;
-webkit-transition: 2s; -o-transition: 2s;
transition: 2s; }
img.tilt:hover {
-moz-transform: rotate(7.5deg); -o-transform: rotate(7.5deg);
-ms-transform: rotate(7.5deg); -webkit-transform: rotate(7.5deg);
transform: rotate(7.5deg);
}


As you’ve seen, creating a smooth and simple animation is easy with CSS3 Transitions. You can modify and
animate almost every aspect of an element’s appearance that CSS properties provide access to. The transitions
I’ve shown you so far have changed only one aspect of an element at a time, and always in the same fashion.
To create richer animations you can combine multiple property transitions for the same element that occur at
different times and speeds.

Free download pdf