Css Animations
Css Animations
AND TRANSITIONS
for the Modern Web
STEVEN BRADLEY
CSS ANIMATIONS
AND TRANSITIONS
for the Modern Web
STEVEN BRADLEY
PEACHPIT PRESS
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contactpermissions@peachpit.com.
Notice of Liability
The information in this book is distributed on an As Is basis, without warranty. While every precaution
has been taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by
the instructions contained in this book or by the computer software and hardware products described in it.
Trademarks
Adobe, the Adobe logo, Photoshop, and Illustrator are registered trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and Peachpit was aware of the trademark
claim, the designations appear as requested by the owner of the trademark. All other product names and
services identified throughout the book are used in an editorial fashion only and for the benefit of such
companies with no intention of infringement of the trademark. No such use, or the use of any trade name,
is intended to convey endorsement or other affiliation with thisbook.
Printed and bound in the United States of America
ISBN-13: 978-0-133-98050-9
ISBN-10: 0-133-98050-2
987654321
Ack nowledgments
Acknowledgments
This book is the work of many people. Id like to thank the fine people at Adobe
Press. Thank you Victor, Robyn, David, Virginia, and Terry. Many more people, who Ill never know, have had a hand in producing this bookthank you.
Id also like to thank my family and friends for their general support and encouragement. Thank you, Mom, Dad, David, H, and Kristine.
iii
iv
A bout th e Auth o r
Ta ble of Contents
Table of Contents
Getting Started x
Chapter 1 Introduction 1
Design Layers 2
Animation3
Transitions5
Chapter 2 Transforms 11
Browser Support and Vendor Prefixes 13
2-dimensional Transforms 14
transform-origin Property 16
2-dimensional Transform Functions 21
Nested Transforms 28
Adding Multiple Transforms to an Element 29
The Transform Rendering Model 30
3-dimensional Transforms 33
perspective Property 34
perspective-origin Property 37
transform-style() Property 39
backface-visibility() Property 43
3-dimensional Transform Functions 52
Summary55
vi
Ta ble o f Co ntents
Chapter 3Transitions57
Browser Support 58
Transitions59
transition-property Property 62
transition-duration Property 66
transition-timing-function Property 68
transition-delay Property 79
transition shorthand Property 81
Summary92
Chapter 4Animations93
Browser Support 95
Detecting Browser Support 95
Finding JavaScript Libraries for Animation 95
CSS Animations 96
CSS Positioning 96
Smoothing the Animation 98
Ta ble of Contents
Summary146
vii
viii
Ta ble o f Co ntents
Chapter 6Examples211
How to Use the Examples 212
Navigation Bar 213
Modal Windows 224
Off-canvas Sidebar Navigation 242
Off-canvas Navigation/Sidebar: Take 1 243
Off-canvas Navigation/Sidebar: Take 2 259
AppendixResources291
Chapter 1: Introduction 292
Browser Support 292
Polyfills292
Ta ble of Contents
Index298
ix
Ge t ti n g Sta rted
Getting Started
CSS continues to evolve as a language, and as it does it gives us a greater ability to create with code. Transforms, transitions, and CSS animations are good
examples of things we could create only in graphics and animation editors. The
file size of a few lines of code is measured in bytes. The size of a file containing
a moving graphic is measured in megabytes and requires an additional request
to the server. For the sake of performance, look first to doing things with code.
The recent design trend has been to remove signals of depth and other details
used to mimic realistic objects on the screen. Unfortunately, some of those
details also serve a purpose in communicating information in websites and
web apps. Motion is replacing depth as the way to communicate whats been
removed and adding back delight in a way thats more in tune with the fluid
and dynamic nature of the web.
This book will start you on your path to adding motion to your designs. It will
show you how to work with transforms, transitions, and CSS animations in
modern browsers, and it will show you how to make changes to CSS properties over time instead of instantly.
The basics covered in this book will help you understand how to create more
realistic animation and present some practical examples you can apply to the
websites you design and develop.
Getting Started
over which these changes occur so they appear more natural. Subtle changes
will add a touch of realism and not be so jarring.
Transitions have a couple of limitations. First, they occur in response to some
action, such as hovering over an element. We cant initiate a transition without some interaction by a site visitor. Second, you have only a single starting
point and a single end point.
CSS animation isnt bound by either of these limitations. You can set an animation to start on its own (or in response to user action). Using keyframes,
you can add as many or as few points between the beginning and end where
you can make additional changes.
At times, youll want to use transitions and at other times youll prefer animation. Ill mention some of these throughout the book.
Once you understand how to work with transforms, transitions, and animations, and have some idea when to use them in real-world projects, well take
a look at the real world again and think about how you can make your animation more realistic.
book listed.
xi
xii
Ge t ti n g Sta rted
Getting Started
In code listings throughout the book, a single line of code onscreen might wrap
to two lines in the book. If this happens, the continued line will start with an
arrow, so it might look like this:
The beginning of the code starts here,
p but it continues on this line.
Code that you should type or modify or that you should pay particular attention to appears highlighted.
-webkit-transform: translateY(0px) scale(1,1);
-ms-transform: translateY(0px) scale(1,1);
transform: translateY(0px) scale(1,1);
<div class="ball"></div>
</div>
The reason for the .stage div is to provide a frame for the animation.
Because you and I are probably looking at browsers open to different widths
and heights, it would be hard to use the browsers edge as the thing the ball
bounces against. By creating a stage for the ball, we can including it in the
animation and make it more likely were both seeing the same thing.
Each example that has a matching file containing all the code is identified in
the text:
Well get to those functions momentarily, but for now lets take a look at a simple example showing a transform (Example 2.1).
xiii
xiv
Ge t ti n g Sta rted
Tools Required
Although tools like Adobes Edge Animate or Tumults Hype 2 can create animation for us, we wont be using them in this book. We wont be using Photoshop or Maya or any other tool that can create movement. These are all great
tools, but were going to create movement by writing code.
That means that the tool requirements are minimal and you should already
have everything you need. Youll need a code editor, a modern browser, and
working knowledge of HTML and CSS. Oh, and bring your imagination.
If you build websites with any regularity, you probably have a favorite code
editor, and youre free to use it. In the following sections, youll find a few you
can try if you dont yet have a favorite or just want to try a few new ones. All
the editors listed can be downloaded and used for free.
Ill be using Adobe Brackets (http://brackets.io). This is an Adobe book after
all, but thats not the only reason for using it. Brackets is free and open source
under an MIT license.
Getting Started
Universal
Brackets: http://brackets.io
jEdit: www.jedit.org
Komodo Edit: http://komodoide.com/komodo-edit
KompoZer: http://kompozer.net
Sublime Text: www.sublimetext.com (free if you dont mind a little nagging)
Aptana Studio: www.aptana.com/products/studio3
Eclipse: www.eclipse.org
Emacs: www.gnu.org/software/emacs
Vim: www.vim.org
Bluefish: http://bluefish.openoffice.nl/index.html
OS X
Text Wrangler: www.barebones.com/products/textwrangler
SubEthaEdit: www.codingmonkeys.de/subethaedit
xv
xvi
Ge t ti n g Sta rted
Windows
Notepad++: http://notepad-plus-plus.org
EditPad Lite: www.editpadlite.com
HTMLKit: www.chami.com/html-kit
Linux
Gedit: https://wiki.gnome.org/Apps/Gedit
Kate: http://kate-editor.org
Chapter 4
ANIMATIONS
CSS transitions offer you a way to create simple animations that always start
as the result of triggering a CSS property change. Transitions can animate only
between a start and end state, and each state is controlled by existing CSS property values. For example, a transition that runs on hover transitions between
values on the element and values on the hover state of the element. Overall,
transitions are a simple way to animate but offer little control over the animation.
CSS animations provide a bit more control. They allow for the creation of multiple keyframes (Figure 4.1) over which the animation occurs. While they can
start in reaction to a change in CSS property value, they can also run on their
own. An animation executes as soon as the animation property is applied.
94
Figure 4.1
Animation keyframes
Transitions can change only between two states.
Transitions dont change property values; they define how the change occurs.
Animations can change property values inside each keyframe.
Transitions change implicitly. You define things at the start and end states, and
you leave it to the browser to determine all the intermediate states. Animations
change explicitly. The animation can define start and end states as well as some
intermediate states. The browser still determines the intermediate states between
keyframes, but the animation gets to define as many keyframes as it wants.
All the things you could change when working with transitions, you can still
change when working with animations. You determine how long the animation lasts and what timing-function to use between keyframes. You also
get to delay the animation if you like.
In addition, you can decide how many times the animation should run and
in which direction it should run. You can set the animation to be running or
paused. You can even determine which CSS property values apply outside the
time frame in which the animation runs.
Animations have other benefits over transitions as youll see in this chapter.
In general, these benefits are about giving you more control. Transitions have
advantages over CSS animations, too. In general, theyre about the simplicity
of transitions.
Ch a pter 4 A n i m ations
Browser Support
Browser support for CSS animations is good. Its similar to what you saw earlier for transforms and transitions. CSS animations work in all modern browsers. In IE10 and newer, Firefox, and IE Mobile, no vendor prefixes are needed.
Safari, Chrome, Opera, iOS Safari, Android Browser, and Blackberry Browser
all use the -webkit vendor prefix, so you have only the one prefix to deal with.
The animation-fill-mode property isnt supported in Android below version
2.3. In iOS 6.1 and earlier, animations arent supported on pseudo-elements.
As you probably expect by this point, the holdouts are Opera Mini and IE9
and earlier. Unfortunately, theres no polyfill like there was for transforms
and transitions. The fallback is to create the animation using JavaScript: You
first check to detect CSS animation support and then use one of the available
JavaScript libraries for working with animation.
JavaScript animation is beyond the scope of this book, but the following section gives you to a few places where you can find more information.
95
96
You could create animations for every browser using JavaScript and ignore
CSS animations completely. If youre using JavaScript to create the animation
for some browsers, why not use JavaScript for all browsers and not worry so
much about CSS animation support? CSS animations are usually, though not
always, more performant than the same animation in JavaScript.
Another option, and the one I recommend, is to treat CSS animations as part
of the noncritical experience. Use animations to enhance the design and the
designs aesthetic, but make sure nothing breaks in browsers that dont support
CSS animations. Your site should still work in any browser that doesnt support
animations, but it can provide a more enjoyable experience for those that can.
Note that while CSS animations work in modern browsers, you dont necessarily see the same smoothness. A smooth-running animation in one browser
might look a bit jerky in another, and its not always the same browsers looking
smooth or not. It depends on the browser and the specifics of the animation.
CSS Animations
As weve been doing throughout this book, lets start with an example.
CSS Positioning
Youll make a box slide across the screen from left to right in two ways. The
first way will be to use CSS positioning (Example 4.1).
1. Add a div with a class of box to your HTML.
<div class="box"></div>
2. Give the .box div dimensions and a background color so you can see it
on the page. Set its position to absolute. Top and left values will be 0
by default, which is fine for this example.
.box {
width: 200px;
height: 200px;
background-color: #393;
position: absolute;
Ch a pter 4 A n i m ations
You need two components to create the animation. The first one declares
the animation on .box. Part of the benefit of the animation property is
the name of a keyframe where youll change properties, so you also need
to create this keyframe, which is the second component.
3. Add the animation property to .box.
.box {
The first value in the list is slide, which is the name of your keyframe.
4. Create the slide keyframe.
@-webkit-keyframes slide {
from {
to {
left:0
left: 600px
}
@keyframes slide {
from {
to {
left: 0;
left: 600px;
97
98
Instant return
from {
left: 0;
}
to {
left: 600px;
}
The animation itself probably wasnt very smooth, but youll get to that in a
moment. Lets talk about what the code is doing, starting with the keyframe.
The keyframe has the name slide. It includes two declarations for the left
property, once in a from state and once in a to state. In the from state, the
left value is 0, and in the to state, the value is 600px. The states from and
to represent the start and end states, so initially the .box is positioned 0 pixels from the left edge, and at the end of the animation cycle, it is 600 pixels
from the left edge.
To start the animation, you set the animation shorthand property on the .box div.
animation: slide 5s linear 0s 3;
The animation is calling the keyframe named slide, and it runs for a duration of 5 seconds. The timing-function is linear. Theres no delay, and the
animation is set to run three times.
Ch a pter 4 A n i m ations
1. Replace the keyframe in step 4 of Example 4.1 with the following keyframe:
@-webkit-keyframes slide {
to {
}
@keyframes slide {
to {
In this code, the translate function moves the .box div 600 pixels to
the right, the same as the left values did in the previous @keyframes
rule. Notice that only the to state is included this time. You dont need to
include a from state. You really didnt need it the first time either. The initial state of the .box div as set on the .box class is exactly what you want
for the from state, so there isnt a need to explicitly set it in the keyframe.
2. Reload your page with this new keyframe.
The same thing happens as before: A green .box moves 600 pixels to the
right three times (Figure 4.3). However, this time the animation runs
smoother. Well get to why at the end of the chapter. For now just know
there are multiple ways to create an animation (or a transition), but the
performance of each way can vary.
99
100
Figure 4.3
Slide animation using
translate function
Instant return
from {
}
to {
-webkit-transform: translate(600px, 0px);
-ms-transform: translate(600px, 0px);
transform: translate(600px, 0px);
}
As you can see in the example, animations can reset CSS property values inside
their keyframes. Transitions cant do this. Although CSS animations affect
property values while running, they dont by default control values before the
animation starts or after it ends. By default, the intrinsic styles (styles added
directly to the element and not inside keyframes) of the element control the
values outside the time the animation is running. The styles set in the keyframe
are in control while the animation is running, but not necessarily before or
after. You do have a measure of control to change the default.
Its possible to have multiple animations running at the same time and for each
animation to set different values on the same property. When this happens,
the animation defined last in the list of keyframe names overrides the other
animations, and the value it sets is used.
Animations can start in one of two ways:
On page load
In reaction to a CSS property change
The start time of an animation is the latter of the time when the style specifying the animation changes (changing the element on hover for example) or
the time the documents load event is firedin other words, automatically
after the page has loaded.
Ch a pter 4 A n i m ations
0% {
20% {
40% {
left: 0;
left: 100px;
left: 200px;
101
102
60% {
80% {
100% {
left: 300px;
left: 400px;
left: 500px;
from {
20% {
40% {
60% {
left: 0;
left: 100px;
left: 200px;
left: 300px;
Ch a pter 4 A n i m ations
80% {
to {
103
left: 400px;
left: 500px;
from more than one @keyframes rule. When multiple @keyframes have been
specified on the animation-name property, the last one in the list (ordered by
time) with a matching @keyframes rule controls the animation.
Its valid for an @keyframes rule to be empty, and because of this it can be
used to hide keyframes previously defined. The empty @keyframes rule should
come later in your CSS to override any @keyframes rule with the same identifier that appears earlier in your CSS.
1. Add the following after the @keyframes rules you set in Example 4.1.
@-webkit-keyframes slide {
}
@keyframes slide {
}
Note
Im using the words
keyframe and
keyframes in ways that
might be confusing.
Each percentage value
represents a new
keyframe or state with
its own CSS property
values. Together the
properties and values in
each keyframe make up
a keyframe declaration
block. The @keyframes
rule is the special
@ rule that contains all
the different keyframes
(states) that an animation
runs through.
104
2. Reload your webpage. The animation should no longer run, since an empty
animation-* Properties
CSS animations offer eight different properties for controlling an animation.
Some are comparable to similarly named transition-* properties, and some
will be new.
animation-name Property
The animation-name property defines a comma-separated list of animations
to apply to the given selector. Its similar to the transition-property in that
it ultimately defines the properties that are animated. With the transitionproperty, those properties are explicitly named. With the animation-name,
an @keyframes rule is explicitly named, and that rule contains the properties
that will be animated.
-webkit-animation-name: slide, drop;
animation-name: slide, drop;
properties: values;
}
@keyframes slide {
}
properties: values;
Ch a pter 4 A n i m ations
@-webkit-keyframes drop {
properties: values;
}
@keyframes drop {
properties: values;
to change the value of the same property on an element, the animation closest to the last name in the animation-name list controls the property values.
If multiple animation-names are listed and one is removed, it stops running,
but the other listed animations continue.
Every listed animation-name should have a corresponding value for any other animation-* properties. If there are too many values in an animation-*
property, any leftover values are ignored. If there arent enough values, the list
of values will be repeated until there are enough to match.
Animations are applied to elements with an animation-name value that matches the name of an @keyframes rule. Once applied, the animation runs. It runs
once the page loads unless its been applied to a trigger, such as :hover. Once
started, an animation continues to run until it finishes or the animation-name
value is removed, such as removing the :hover on the animating element.
An animation ends based on some combination of the animation-duration,
animation-iteration-count, and animation-fill mode properties. You
can also end an animation by setting the animated elements display property to none. This also ends any animations running on descendant elements.
105
106
Note
When an animationname is added to the
:hover state of an
element, removing the
hover also removes the
animation-name, and
the animation stops.
animation-duration Property
The animation-duration property defines how long an animation lasts
during one cycle of the animation. Its similar to the transition-duration
property and takes a time value in seconds (s) or milliseconds (ms).
-webkit-animation-duration: 10s;
animation-duration: 10s;
0% {
50% {
property: value;
property: value;
Ch a pter 4 A n i m ations
100% {
property: value;
the animation will take 10 seconds to get from 0 percent to 100 percent, and
not 10 seconds to go from 0 percent to 50 percent and then 10 seconds more
from 50 percent to 100 percent.
Similarly, when an animation is set to loop multiple times, the animationduration is the time it takes to complete one loop or cycle.
animation-timing-function Property
The animation-timing-function property describes an acceleration curve
for each keyframe in a single animation cycle. Its similar to the transitiontiming-function. You can use any of the keyword timing functions or create one of your own.
animation-timing-function: step-start;
animation-timing-function: step-end;
animation-timing-function: steps();
animation-timing-function: ease;
animation-timing-function: linear;
animation-timing-function: ease-in;
animation-timing-function: ease-out;
animation-timing-function: ease-in-out;
animation-timing-function: cubic-bezier();
107
108
<div class="box"></div>
2. Give the .box class dimensions and a background-color.
.box {
width: 200px;
height: 200px;
background-color: #393;
}
3. Add an animation to the .box div using the individual animation-*
properties.
.box {
-webkit-animation-name: slide;
animation-name: slide;
-webkit-animation-duration: 5s;
animation-duration: 5s;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
4. Finally add an @keyframes rule to your CSS.
@-webkit-keyframes slide {
0% {
Ch a pter 4 A n i m ations
25% {
50% {
75% {
100% {
}
@keyframes slide {
0% {
109
110
25% {
50% {
75% {
100% {
This code adds five keyframes to the @keyframes rule. This should make
it easier to see that the ease-in timing function is running between each
keyframe and not once over the entire animation cycle.
Ch a pter 4 A n i m ations
111
5. Load your page in a browser, and observe the timing curve between key-
Figure 4.4
Animation timing functions
0%
25%
50%
75%
100%
You can override the timing function inside each of the keyframes. When a
timing function is applied inside a keyframe, its instructing the animation
to use that function moving from the keyframe with the timing function
applied to the next one (Example 4.4).
6. Replace your @keyframes slide rule from Example 4.3 with the follow-
0% {
25% {
112
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
50% {
75% {
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
100% {
}
@keyframes slide {
0% {
Ch a pter 4 A n i m ations
25% {
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
50% {
75% {
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
100% {
In this code, you override the ease-in timing function on two of the
keyframes.
113
114
7. Reload your page, and observe the difference in the acceleration curve
Figure 4.5
Animation timing functions
on keyframes
0%
Ease-in
25%
50%
75%
100%
Linear
Ease-in
Linear
Ease-in
The way timing functions work over keyframes and the ability to override them
on a specific keyframe is powerful and perhaps a bit scary. You have great control over how your animation accelerates, but you also have the responsibility
to exercise that control. Having an animation ease in between every keyframe
is probably not what you want.
animation-iteration-count Property
Transitions run once when triggered and run once in reverse when the trigger
is removed. Animations can run as many times as you want. The animationiteration-count property defines how many times an animation runs, and
it takes as a value any number or the keyword infinite. The latter sets your
animation to run in an endless loop.
-webkit-animation-iteration-count: 3;
animation-iteration-count: 3;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
Ch a pter 4 A n i m ations
Youve already seen the animation-iteration-count in action in Example4.1, although that example used the animation shorthand to set all the values. Because you might be getting tired of sliding boxes and because the rest
of the examples in this chapter are variations of that same sliding box, lets do
something different here (Example 4.5).
1. Start by adding a div with a class of box to your HTML.
<div class="box"></div>
2. Instead of giving dimensions and a background-color to the .box div,
set the dimensions to 0px, and add a border with different colors for each
side. Finally, give the border a radius of 50%.
.box {
width: 0px;
height: 0px;
border-width: 100px;
border-style: solid;;
border-radius: 50%;
}
3. Load your page.
-webkit-animation-name: rotate;
animation-name: rotate;
-webkit-animation-duration: 4s;
animation-duration: 4s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
115
116
-webkit-animation-iteration-count: 3;
animation-iteration-count: 3;
}
5. Create the rotate @keyframes rules to rotate the .box div.
@-webkit-keyframes rotate {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
25% {
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
50% {
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
75% {
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
Ch a pter 4 A n i m ations
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
@keyframes rotate {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
25% {
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
50% {
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
117
118
75% {
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
6. Load your code in a browser.
Figure 4.6
Animation iteration count
If you followed the colors in the example for the borders, the green wedge
should start at the top. Each time the green wedge is back at the top is one
iteration or one animation cycle (Figure 4.6).
One iteration of an animation
0% {
50% {
100% {
transform: rotate(0deg);
transform: rotate(180deg);
transform: rotate(360deg);
}
}
}
75% {
25% {
transform: rotate(270deg);
transform: rotate(90deg);
}
}
Ch a pter 4 A n i m ations
animation-direction Property
Another new property is the animation-direction property, which defines
whether an animation runs forward or in reverse on some or all of its cycles.
The animation-direction property takes one of four values:
normal specifies that all iterations of the animation are played as specified.
reverse specifies that all iterations of the animation are played in the
reverse direction as specified.
alternate causes the cycles to alternate between normal and reverse
with normal for the first cycle and all odd iteration counts. Even counts
are reversed.
alternate-reverse causes the cycles to alternate between normal and
reverse with reverse for the first cycle and all odd iteration counts. Even
counts are normal.
-webkit-animation-direction: normal;
animation-direction: normal;
-webkit-animation-direction: alternate-reverse;
animation-direction: alternate-reverse;
When the animation plays in reverse, the timing functions also run in reverse
for example, ease-in runs as ease-out.
Until now, the sliding box youve been working with slides to the right and
then instantly returns to its initial location. The jump is more than a little jarring. The alternate and alternate-reverse values can remove the jump.
Instead, the box continues to slide right and left until the animation stops.
Lets go back to the sliding .box div youve used through most of this chapter (Example 4.6).
1. Start by adding a div with a class of box to your HTML.
<div class="box"></div>
119
120
.box {
width: 200px;
height: 200px;
background-color: #393;
}
3. Add the animation-* properties to .box. Additions to the code are
highlighted.
.box {
-webkit-animation-name: slide;
animation-name: slide;
-webkit-animation-duration: 5s;
animation-duration: 5s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: 3;
animation-iteration-count: 3;
-webkit-animation-direction: reverse;
animation-direction: reverse;
Ch a pter 4 A n i m ations
@-webkit-keyframes slide {
to {
}
@keyframes slide {
to {
}
5. Load your page.
First it jumps 600 pixels to the right (so fast that you might not see the .box
on the left before the jump), and then it slides back to its initial location
and repeats the sequence three times.
6. Change the value for the animation-direction in step 3 to alternate
(Example 4.7).
-webkit-animation-direction: alternate;
animation-direction: alternate;
7. Reload your page, and observe the difference (Figure 4.7).
Now the .box div slides back and forth between the initial and ending
states. This makes for a much smoother overall animation. Experiment with
the normal and alternate-reverse values.
121
122
Figure 4.7
Animation direction
Iteration 1 runs normally.
animation-play-state Property
By default, your animations run as soon as the animation-name property is
assigned. You can change that behavior with the animation-play-state
property, which defines whether an animation is running or paused.
-webkit-animation-play-state: running;
animation-play-state: running;
-webkit-animation-play-state: paused;
animation-play-state: paused;
The default value, as you would likely guess, is running. If you change the
value to paused, the animation stops where it is until the animation-playstate is changed again to running. When paused, the animation displays
whatever state the animation was in at that moment. When the animation is
resumed, it restarts from the state it was paused in.
Ch a pter 4 A n i m ations
-webkit-animation-name: slide;
animation-name: slide;
-webkit-animation-duration: 5s;
animation-duration: 5s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: 3;
animation-iteration-count: 3;
-webkit-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-play-state: paused;
animation-play-state: paused;
}
2. Reload your page.
Unlike previous examples, this time the animation doesnt run when the page
is finished loading. To run the animation, you need to change animationplay-state to running and reload the page.
This isnt particularly useful if you have to reload the page after changing
the animation-play-state property, but it becomes much more useful
when changing properties via JavaScript or some other trigger.
Lets modify the example to add triggers.
123
124
<div class="container">
<button id="play">Play</button>
<button id="pause">Pause</button>
</div>
The buttons get ids so your JavaScript code has something to hook into.
Notice that the code adds an id of box to the .box div.
The buttons need some styling.
4. Add the following to your CSS:
button {
border-radius: 5%;
margin-top: 3em;
Nothing special. Just a little style to make your buttons look buttony. Now
lets add some JavaScript so the buttons do something.
5. Add the following code in the head of your document between <script>
</script> tags.
<script>
var init = function() {
Ch a pter 4 A n i m ations
document.getElementById('play').addEventListener(
p 'click', function(){
box.style.webkitAnimationPlayState = "running";
box.style.animationPlayState = "running";
}, false);
document.getElementById('pause').addEventListener(
p 'click', function(){
box.style.webkitAnimationPlayState = "paused";
box.style.animationPlayState = "paused";
}, false);
};
window.addEventListener('DOMContentLoaded', init, false);
</script>
Hopefully, the script looks somewhat familiar. The last line of code listens
for the page to load and then calls the init function.
Inside the function, you first get hooks to each button and the .box div and
set them to appropriately named variables. Next you add event listeners to each
button, and if a button is clicked, you set the value of animationPlayState
to either running or paused, depending on which button was clicked.
6. Reload your page one more time.
You should see the new play and pause buttons. The green box sits in the
top-left corner until you click the Play button to start the animation. Once
the box begins moving, you can click the Pause button to stop the animation. Clicking Play starts the animation again from the point at which it
was stopped.
animation-delay Property
The animation-delay property defines when an animation starts. It works
the same way the transition-delay property works. Like transitiondelay, values are in units of time and can be positive, 0, or negative.
125
126
-webkit-animation-delay: 2s;
animation-delay: 2s;
-webkit-animation-delay: 0s;
animation-delay: 0s;
-webkit-animation-delay: -2s;
animation-delay: -2s;
A positive value delays the animation until some point in the future. A value
of 0 (the default) starts the animation instantly. A negative value appears to
start the animation in the past. It starts instantly, but at a point in the middle
of the animation. The delay works as an offset.
Lets continue to build on Example 4.8.
1. Add an animation-delay to the .box div. Additions to the code are
-webkit-animation-name: slide;
animation-name: slide;
-webkit-animation-duration: 5s;
animation-duration: 5s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: 3;
animation-iteration-count: 3;
-webkit-animation-direction: alternate;
animation-direction: alternate;
Ch a pter 4 A n i m ations
-webkit-animation-play-state: running;
animation-play-state: running;
-webkit-animation-delay: 2s;
animation-delay: 2s;
}
2. Reload your page.
The animation does nothing for 2 seconds and then slides back and forth like
before (Figure 4.8). Try using some negative values, and observe the difference.
0s
1s
2s
3s
4s
5s
0px
200px
400px
2s delay
Begin animation
600px
Figure 4.8
Animation delay
127
128
animation-fill-mode Property
You probably had an idea what each animation-* property did before I told
you. Some were familiar after working through transitions, and the property
names give a pretty good clue about what the others do.
The animation-fill-mode property is probably not intuitive to you. You
might be thinking about background colors filling your element or something
like that. The animation-fill-mode property actually defines what values
are applied by an animation outside of its execution time.
By default, an animation affects property values only while its running. This
is why the example animations youve been working with often jump back to
the initial state when the animation stops. Whatever values are set in each keyframe are the ones used for a property until either the next keyframe changes
it or the animation stops playing. When the animation stops, the CSS property
values are whatever values were set intrinsically on the element.
The animation-fill-mode property overrides this behavior. It takes four
keyword values.
animation-fill-mode: none | forwards | backwards | both
none is the default, and it doesnt apply any property values in the animation outside the animations execution.
backwards applies the property values defined in the first keyframe that
starts the first iteration to the period defined by animation-delay. The
values come from either the 0% (from) or 100% (to) keyframes, depending on the value of the animation-direction property.
forwards applies the property values after the animation stops. If the
animation-iteration-count value is greater than 0, the values applied
are those at the end of the last completed iteration. If the count value equals
0, the values applied are those that start the first iteration.
both does what you might expect and applies both the forwards and
backwards values to the animation-fill-mode property.
Ch a pter 4 A n i m ations
Once again lets expand the example weve been working with.
1. Add an animation-fill-mode to the .box div. Additions to the code are
-webkit-animation-name: slide;
animation-name: slide;
-webkit-animation-duration: 5s;
animation-duration: 5s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-webkit-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-play-state: running;
animation-play-state: running;
-webkit-animation-delay: 2s;
animation-delay: 2s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
129
130
As before, the green box slides to the right when the animation begins.
However, now when it stops it doesnt jump back to its initial state. Setting
the animation-fill-mode to forwards allows the .box div to hold the
final state in the animation after the animation completes (Figure 4.9).
Figure 4.9
Animation fill mode
Initial state
Final state
Slide animation
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
Or add a 0% (or from) keyframe in the @keyframes rule so the .box begins
the animation in a different location.
0% {
Ch a pter 4 A n i m ations
131
For both changes, observe where the .box div is located before and after the
animation as well as during the animation-delay.
If you replace each of the properties with a value, you get something like this:
animation: slide 2s ease 0.5s 2 reverse both running;
To add multiple animations, you separate each definition with a comma like this:
animation: slide 2s ease 0.5s 2 reverse both running,
p bounce 5s ease-in-out 0 3 alternate forwards paused;
Note that the comma occurs between the full definition for each animation.
There are two definitions in this line of code, so a single comma between them
is all you need.
As with transitions, order is important. Just as with the transition shorthand,
the first time value is assigned to the animation-duration property, and the
second time value is assigned to the animation-delay property.
Animation Events
You learned in the last chapter that when a transition completes, it generates
a DOM event. Animations also fire events. They fire an event at the start and
end of an animation as well as the end of each iteration.
Note
The current animation
spec mentions a possible
future addition. At
some point, a / notation
might be added to
the shorthand. If that
happens, youll be able
to specify duration and
delay as 10s/2s, where
the numerator (10s) is
the duration and the
denominator (2s) is the
delay. This doesnt work
now, but is a future
possibility.
132
Ch a pter 4 A n i m ations
Lets try an example so we can experiment with these events and their associated values. Youve been working with variations of the same example. Why
stop now? Youve made the box slide to the right and most of the time back to
the left. Lets add another @keyframes rule that generates a downward slide.
Youll apply this new rule after the .box finishes the slide animation.
The animation will slide to the right, slide back to its initial position, and then
slide down and back up again (Example 4.11).
1. Add div with a class of box and an id of box to your HTML.
The class is used to style the div like youve been doing all along, and the
id is used to hook into the element via JavaScript. The class name and
id name dont need to be the same. You just need to make sure to match
the names you give them in the appropriate place in the code.
on the page, and then add an animation using the animation shorthand.
.box {
width: 200px;
height: 200px;
background-color: #393;
Before creating the @keyframes rule, take a look at the shorthand in this
code, and make sense of what its doing. Its calling an @keyframes rule
named slide. Each animation cycle runs a total of 2 seconds. The timing
is linear so there is no acceleration. Theres no delay, and the animation
completes two cycles. It runs once normally and then runs in reverse. Animation elements hold their state both before and after the animation runs.
133
134
3. Create the @keyframes rule using translation to move the element 600
100% {
}
@keyframes slide {
100% {
}
4. Load the page in a browser.
The familiar green .box slides to the right and then slides back left to its
starting point. This animation fires events. Youll capture those events using
a little JavaScript. Dont worry, its no more complicated than what you did
in the last chapter with transition events, and youre free to copy the code.
What youre going to do is listen for one of the animation events and when
it occurs, start a second animation. The .box is probably getting tired of
sliding across the page so a slidedown @keyframes rule seems in order.
Ch a pter 4 A n i m ations
lation transform, and make the .box move 300 pixels down the screen.
@-webkit-keyframes slidedown {
to {
}
@keyframes slidedown {
to {
You can reload your page if youd like, but Ill save the suspense. Nothing
changes. Youve created a @keyframe rule, but its not attached to any element yet. Thats where the events and JavaScript come in.
6. Add the following JavaScript between <script></script> tags in the
<script>
var init = function() {
135
136
box.addEventListener("webkitAnimationStart",
p updateAnimation , false);
box.addEventListener("oTAnimationStart",
p updateAnimation , false);
box.addEventListener("animationstart",
p updateAnimation , false);
box.style.webkitAnimationName = "slidedown";
box.style.animationName = "slidedown";
};
window.addEventListener('DOMContentLoaded', init, false);
</script>
The JavaScript is a modified version of what you saw with transition events.
The last line of code, window.addEventListener('DOMContentLoaded',
init, false);, once again runs an init function after the page content loads.
In the init function, you first get the element with an id of box and assign
it to a variable named box. Next, you add an event listener (with and without
vendor prefixes) to the box to capture an animationstart event. When
the event is captured, its passed to an updateAnimation function. Finally
the updateAnimation function changes the animation-name value to
the slidedown animation created in step 5.
7. Reload your page, and observe what happens.
The second animation (slidedown) runs, but the first one (slide) doesnt.
This happens because the JavaScript captures the event that fires at the start
of the animation and changes which animation is used before slide can run.
Lets capture a different event (Example 4.12).
Ch a pter 4 A n i m ations
box.addEventListener("webkitAnimationIteration",
p updateAnimation , false);
box.addEventListener("oTAnimationIteration",
p updateAnimation , false);
box.addEventListener("animationiteration",
p updateAnimation , false);
box.style.webkitAnimationName = "slidedown";
box.style.animationName = "slidedown";
};
window.addEventListener('DOMContentLoaded', init, false);
</script>
9. Reload your page.
The slide animation starts and completes a single cycle before it jumps
back to its initial state and begins and completes both iterations of the
slidedown animation.
This time you listened for the event that fires at the end of each iteration
of an animation. The slide animation completes one iteration, the
animationiteration event is fired, and your code starts the slidedown
animation. The slidedown animation completes because the JavaScript
code runs only a single time. No code is listening for the events that the
slidedown animation fires in this example.
137
138
10. Change your JavaScript code to listen for animationend, and change
box.addEventListener("webkitAnimationEnd",
p updateAnimation , false);
box.addEventListener("oTAnimationEnd",
p updateAnimation , false);
box.addEventListener("animationend",
p updateAnimation , false);
box.style.webkitAnimationName = "slidedown";
box.style.animationName = "slidedown";
};
window.addEventListener('DOMContentLoaded', init, false);
</script>
11. Reload the page.
This time both animations start and complete. First slide moves the .box
to the right before returning. As soon as it completes, an animationend
event is fired. Your JavaScript hears the event and starts the slidedown
animation, which also completes.
Figure 4.10 summarizes listening for each of the three animation events
and starting the slidedown animation after the slide events fire.
Ch a pter 4 A n i m ations
animationstart
event fires.
animationiteration
event fires.
Iteration 1
slide animation
Iteration 2
Lets do one more thing: read the read-only values. You can access and read
them at each of the three fired events.
12. Change your JavaScript code to listen for the animationstart event,
and set an alert to display the animationName that fired the event and
the elapsedTime its been running. Changes in the code are highlighted.
<script>
var init = function() {
box.addEventListener("webkitAnimationStart",
p updateAnimation , false);
box.addEventListener("oAnimationStart",
p updateAnimation , false);
box.addEventListener("animationstart",
p updateAnimation , false);
139
Figure 4.10
Animation events summary
140
};
window.addEventListener('DOMContentLoaded', init, false);
</script>
13. Reload your page.
As soon as the page loads, the slide animation runs, and an alert pops up
with the message, The slide animation has been running for 0s.
Figure 4.11 shows the alerts that display when listening for the animationiteration event.
Figure 4.11
Animation event read-only
values
Ch a pter 4 A n i m ations
Transition or Animation
One of the questions you might be asking yourself is when you should use a
transition and when you should use an animation. You can create most of the
examples in this and the previous chapter using either transitions or animations. So which should you choose when you want to animate something?
Similarities
You can start to answer that question by thinking about the similarities and differences of transitions and animations. One thing they both have in common
is their properties. About half the animation-* properties have a counterpart
transition-* property. The timing functions, for example, are the same, except
for using the word animation or transition to start the property name.
Both can listen for changes to CSS property values and interact with JavaScript
events. Triggering events like those in the following list can make changes in
CSS property values that start either animations or transitions:
:hover
:link
:active
:visited
:focus
:checked
:disabled
You can also start transitions and animations through changes in media queries or class changes via simple JavaScript that changes the appropriate property values.
141
142
Differences
Lets switch gears and think about the differences. Although both transitions
and animations can run in response to a trigger, only animations can run automatically on page load. Transitions require a trigger to run. If you need your
animation to run automatically, you have only one choice.
Transitions are limited to initial and final state keyframes. Animations can
build as many intermediate keyframes as necessary or desired. This gives you
more control over your animation and allows you to create more complex and
sophisticated animations. Transitions are for simple animations.
Transitions dont change properties. You set values up front in the CSS intrinsic to the specific elements. Transitions define the change only between property values and not the values themselves. Animations can change property
values inside each keyframe. The values dont need to be declared outside the
animation either, making animation more dynamic.
Transitions cant loop. They run once when triggered and then run in reverse
when the trigger is removed. Otherwise they dont run. You can loop animations as many times as you want and set them to run in reverse or alternate
between forward and reverse. Once again CSS animations offer you more control than CSS transitions.
Once you start using JavaScript to further control your transitions and animations, it quickly becomes clear that transitions are easier to work with. Its
more difficult making changes to the values inside keyframes than it is the
intrinsic values on elements.
As a general rule, youll write more code using CSS animations as opposed to
CSS transitions, assuming both are trying to do the same thing.
When you get down to it, animations are abstractions of transitions. States are
pulled out from the specific case to work in a more modular fashion. Transitions are a specific case of the more general animation. If you find yourself
using the same transition code over and over, you might decide to rewrite it
as an animation.
Ch a pter 4 A n i m ations
Performance
The short answer is that you shouldnt see any performance difference between
transitions and animations, assuming both are doing the same thing in the same
way. Performance has more to do with what properties are being changed as
opposed to whether those changes happen through transitions or animations.
To render webpages, a browser first calculates the CSS styles that apply to the
HTML elements. Then it lays out the page by working through the geometry
and position for each element. Next comes painting where pixels are filled in
before finally drawing everything to the screen on composite layers. Browsers
use two different execution threads to do all these things and render webpages:
the main thread and the compositor thread.
The main thread is responsible for laying out pages and painting elements. It
computes the CSS styles applied to HTML elements, and it runs JavaScript.
The compositor thread draws bitmaps to the screen via the graphic processing
unit (GPU). It determines which parts of the page are visible or will soon be
visible. It determines whats likely to be scrolled to next and moves the parts
of the page when someone does scroll. Both threads communicate with each
other, sending and requesting information.
143
144
The main thread tends to be busier for longer periods of time, and while busy
its not responsive to input. The compositor thread, on the other hand, tries to
remain responsive because it has to be aware of scrolling.
Main thread responsibilities are more CPU intensive, while compositor responsibilities look to the GPU more frequently. GPUs can draw the same bitmaps
over and over in different positions quickly. They can scale and rotate bitmaps
quickly as well.
To create more performant animations, you generally want to stay away from
layout and painting changes and instead make compositing changes. Compositing changes can be made on separate compositing layers, so the browser
doesnt need to repaint or rework the layout of other layers.
Table 4.1 lists CSS properties that affect layout and painting.
It turns out that there are currently five things browsers can animate cheaply
in terms of performance: translation, scale, rotation, opacity, and some CSS
filters. The first three should have you thinking back to transforms. Anything
beyond animating these five types of properties probably wont run as smooth.
Consider moving an element to a new location, which is something youve
done a few times throughout this book. You can use a transform to move the
element, or you can adjust properties like top and left. The former uses the
GPU, while the latter uses the CPU. You want to take advantage of the GPU
where possible and take advantage of the hardware acceleration it provides. If
you think back to the first example in this chapter, you moved an element by
adjusting its left value and then by applying a translation transform. The
approach using translation ran smoother, and this is why.
It wont matter whether you use CSS transitions or CSS animations when it
comes to performance, but you should think about performance when creating either. Transforms, opacity, and some CSS filters dont require layout or
painting changes and so are preferred properties for animating.
This doesnt mean you shouldnt animate other properties. You can still create a smooth animation with other properties. Just realize that if you have the
choice, you should opt for changing a transform, opacity, or CSS filter instead
of another property.
Ch a pter 4 A n i m ations
width
color
height
border-style
padding
border-radius
margin
visibility
display
background
border-width
text-decoration
border
background-size
top
background-image
position
background-position
font-size
background-repeat
float
outline-color
text-align
outline
overflow-y
outline-style
font-weight
outline-width
overflow-y
box-shadow
left
right
font-family
line-height
vertical-align
clear
white-space
bottom
min-height
145
146
Summary
In time, you can expect browsers to make more CSS properties quicker to
animate. For now, do what you can with what you have. You have enough
control over both transitions and animations to animate many CSS properties smoothly and create more realistic-looking animations, which brings us
to the next chapter.
298
I N DE X
Index
Symbols
* (asterisk), 47
@keyframes rule
defining and using, 101104
naming with animation-name property,
104105
opening and closing sidebar navigation with,
249254
squash and stretch, 155157
A
absolute positioning, 284
accelerating/decelerating transitions, 6878
ease curves, 74
ease-in curves, 76
ease-out curves, 77
linear curves, 75
actions
adding anticipation to, 159
follow-through and overlapping, 168181
overlapping and secondary action, 195196
staging, 165
straight-ahead and pose-to-pose, 168
triggering transitions with, 58
all keyword, 62, 63
alternating animation directions, 19
animation, 93146. See also animation-* properties;
twelve principles of animation
about, 9394
additional principles of, 208209
anticipation in, 158164
appeal in, 207208
arcs in, 182195
CSS positioning creating, 9698
defining with @keyframes rule, 101104
delaying, 125127
Disneys 12 principles of, 148149, 295296
ending, 105
events in, 131140
exaggeration in, 197206
firing events, 131
follow-through and overlapping action in,
168181
importance in web design, 35, 289
iteration counts for, 114118
JavaScript vs. CSS, 96
keyframes for, 94
looping, 114118, 142, 143
practicing, 290
B
backface-visibility() property, 4351
background color transitions
delaying, 7981
duration of, 6668
occurring when hovering, 6061, 6365
progressive, 6061
step functions for timing changes in, 6971
:before and :after pseudo-elements, 58, 62
body property, 212213
I N DE X
bounce animation
adding arcs to, 182195
adding exaggeration to, 197206
applying solid drawing principle to, 206207
applying squash and stretch principle, 149158
creating anticipation in, 158164
follow-through and overlapping action for,
168181
secondary actions and ball rotation in, 196
slow in and slow out in, 182
staging and context for, 164167
bounding box, 1920
box model
adding padding to, 20
CSS positioning to animate, 9698
generating DOM events after transitions in,
8487
inheritance of transform-origin property in,
1819
layouts in CSS animation, 11
rotating, 1416, 23
starting/reversing transitions of, 8283
box-sizing: border-box property, 47, 212213
browsers. See also IE; Opera Mini
animation support in, 9596, 146
applying transform matrix in, 2628
CSS transforms and transitions supported by,
79
deciding which to support, 287
preventing Webkit browsers from running nonWebkit code, 257
resources on, 292
support and vendor prefixes for, 13, 55
transition and animation performance in,
143144
transition support by, 58, 92
transitioning CSS animatable properties in, 89
buttons
changing text for sidebar navigation, 256258
modal window, 226227
triggering animation play with, 123125
C
card flip
adding to modal window, 234235, 236, 239240
backface-visibility() property for, 4351
Cascading Style Sheets. See CSS
character staging, 164
child elements
controlling 2-D or 3-D rendering of, 3942
creating new origin for, 18
flattening, 3942
rendering in 3-D, 41
rotating around parents div axis, 42
click events in CSS, 231
color. See also background color transitions
adding to background, 1920
navigation bar background, 216217
setting modal window, 228229
containers
adjusting perspective origin of, 3739
code for modal window, 226227
content switcher, 269285
combining transitions on different properties,
285
event listener for, 273275
implementing switch statements for, 275276
listening for page to complete loading, 273
setting up HTML document for, 269270
sliding content block while modifying opacity
and scale, 275282
styling window components of, 270273
coordinate space
stacking contexts in, 3031
3-dimensional, 34
2-dimensional, 12
CSS (cascading style sheets)
adding multiple transforms to elements, 2930
animatable properties available for transitions,
8991
browser support for, 9
choosing transitions or animations, 143
click events in, 231
CSS Shapes Module in future, 11
differences in transitions and animations, 142
overriding preserve-3d value in, 40
polyfills for unsupported, 79
properties affecting layout and painting in,
144,145
similarities in transitions and animations, 141
transformations using, 7
2-dimensional coordinate space for, 12
updated lists of animatable properties, 91
usefulness of JavaScript with, 288
using animations in JavaScript or, 96
visual formatting model for, 1112
CSSSandpaper polyfill, 13
cubic Bzier curves, 69, 7278
defining, 7273
ease curves, 74
ease-in curves, 76
ease-in-out curves, 78
ease-out curves, 77
keywords for, 73, 7478
linear curves, 75
299
300
I N DE X
D
decelerating transitions. See accelerating/decelerating
transitions
delaying
animations, 125127
transition starts, 7981
depth cues, 45
detecting browser support, 95
Disney Animation (Johnston and Thomas), 148
Disney, Walt, 148149
Drawn to Life (Stanchfield and Hahn), 208
drop-down menu for navigation bar, 218223
duration of transitions, 6668
E
easing
ease curves, 74
ease-in curves, 76, 107111
ease in/out animation principle, 182
ease-in-out curves, 78
ease-out curves, 77
effects. See also transforms; transitions
resources on, 296297
elements. See also child elements; pseudo-elements
adding multiple transforms to, 2930
applying multiple transitions to, 6263, 92
delaying start of transitions, 7981
moving to different location, 2122
numeric values when making smaller, 23
scaling, 2223
setting transition duration for, 6668
step functions for timing transitions in, 6971
translating to different location, 2122, 52
ending animations, 105, 132, 139
environment for staging, 164165
event listeners
adding for animation events, 137, 138, 139140
adding JavaScript, 84
setting up for content switcher, 273275
events
buttons triggering animation, 123125
listening for animation, 136, 137138, 139140
resources on, 293, 294
transitions firing, 84, 92
types of animation, 131140
exaggeration, 197206
example code. See also bounce animation; and specific
examples
content switcher, 269285
how to use, 212213
modal windows, 224241
navigation bar, 213223
F
Flash animation, 7
flat value for transform-style property, 39
follow-through, 168181
forms, 227228
functions
cubic Bzier curves, 69, 7278
distinguishing 2-D and 3-D, 52
matrix(), 2528
matrix3d(), 5354
rotate(), 23, 52
scale(), 2223, 52
skew(), 24
step, 6971
3-dimensional, 5254
translate(), 2122, 52
2-dimensional transform, 2128
using multiple transform, 2930
H
Hahn, Don, 208
hiding/showing
front card face, 46
previously defined @keyframes rule, 103
submenu with opacity, 219221
hovering
adding animation-name to elements in
:hover state, 106
changing background color when, 6061, 6365
reversing transitions when removed, 9193
HTML
animation using dynamic, 67
code for modal windows, 225226
drop-down menu code in, 218
setting up content switcher document in,
269270
structuring off-canvas sidebar navigation,
243246, 260261
I
icons for menu items, 247
IE (Internet Explorer)
converting CSS transforms to filters in, 13
transitions using, 58
window.getComputedStyle workaround for,
256
workarounds for inline-block method, 216
workaround for preserve-3d, 42
I N DE X
J
JavaScript
adding event listeners, 84
animation using, 7
changing animation-name property for
off-canvas sidebar, 254257
converting transforms to IE filters with, 13
examples used in transform code, 14
finding libraries for animation, 9596
listening for animation events, 137, 138, 139140
polyfills for unsupported CSS, 79
transitions and ease of control in, 142
usefulness of, 288
using animations in CSS or, 96
Johnston, Ollie, 148
jQuery, 95
K
keyframes. See also @keyframes rule
animation, 94
applying animation-timing-function
between, 107
creating anticipation with, 158164
defined, 101
defining with @keyframes rule, 101104
overriding timing functions in, 111, 113, 114
placement of transitions and animations in, 142
resetting property values in, 100
setting up timing with, 197
keywords
all, 62
animation-fill-mode, 128
Bzier curve, 73, 7478
perspective-origin, 37
transform-origin, 17
L
layers of design needs, 23, 288
laying out pages, 143145
length values in perspective property, 34
libraries for JavaScript animation, 9596
linear curves, 75
links for navigation bar, 214217
list items
adding for drop-down menu, 218
displaying horizontally, 215
selecting, 215216
looping
animations, 114118, 142, 143
unavailable with transitions, 142
M
matrix math, 2526, 29
matrix() function, 2528
matrix3d() function, 5354
measurements in translate() function, 22
mobile device navigation, 243
modal windows, 224241
adding card flip to, 234235, 236
code for opening/closing overlay, 229231
container and button code for, 226227
debate over, 224
form labels for, 227228
HTML code for, 225226
illustrated, 224225
moving offscreen, 232234
scaling to final size, 236237
setting color and opacity for, 228229
shrinking, 237239
using multiple transitional effects in, 239240
motion. See animation
moving elements to different location, 2122
ms vendor prefix, 5, 13
multiple animations, 100
N
naming transform property, 16
navigation. See navigation bar; off-canvas sidebar
navigation
navigation bar, 213223
drop-down menu for, 218223
illustrated, 213
links for, 214216
selecting list items from, 215216
setting background color for, 216217
setting up horizontal elements for, 215
nested transforms, 28
numbers
about matrices, 2526
values for making elements smaller, 23
O
objects
applying principle of solid drawing to, 206207
arcs and motion of, 182183
rotating around axis, 23
setting origin of transformed, 1620
301
302
I N DE X
objects (continued)
skewing, 24
slow in and slow out of, 182
squashing and stretching, 149158
staging characters and, 164
visibility of back side of transformed, 4351
off-canvas sidebar navigation, 242268
adding animation-* properties to, 248249
@keyframes rules for opening/closing, 249254
HTML code for layout, 243244
icons for menu items, 247
JavaScript changing animation-name property,
254257
layout for four divs, 244247
open and closed, 242
preventing Webkit browsers from running nonWebkit code, 257
second version of, 259268
suggested enhancements for, 259
opacity
changing as content block slides outside window,
280
combining with scaling effect, 277279
hiding/showing elements used by browsers, 229
hiding/showing submenu with, 219221
setting modal window, 228229, 231232
transition for changing, 231232
opening/closing modal window overlay, 229231
Opera Mini
oTransitionEnd event, 84
transforms with, 13
transitions using, 58
overlapping action, 181, 195196
overriding
@keyframes rule, 103
preserve-3d value, 40
timing functions in keyframes, 111, 113, 114
P
padding for bounding box, 20
painting elements, 143145
parent elements
flattening child element on, 3942
rendering child element in 3-D, 41
rotating child around parents div axis, 42
performance
resources on, 294295
of transitions and animations, 143144, 217
perspective function, 53
perspective-origin property, 3739
perspective property
about, 55
setting up 3-dimensional look with, 3437
polyfills
applying transitions in IE with, 58
resources on, 292
Transformie and CSSSandpaper, 13
pose-to-pose action, 168
positioning
animating box model with CSS, 9698
relative, 285
using absolute, 284
practicing animation principles, 290
preserve value for transform-style property,
39,40, 42
progressive enhancement
designing with, 243, 288289
suggestions for sidebar navigation, 259
properties
affecting layout and painting, 144, 145
applying values to completed animations, 128
CSS animatable, 8991
effect of transitions and animations on, 142
resources on animatable, 294
setting different values for multiple animation, 100
setting values on transition-*, 92
3-dimensional transform, 3452, 55
2-dimensional transform, 1620, 55
using asterisk in, 47
pseudo-elements
:before and :after, 58, 62
support for, 95
R
realistic animation, 147148, 295
relative positioning, 285
rendering child element in 3-D, 41
resizing. See scaling
resources
animation, 294295
browser support, 292
detecting browser support, 95
effects, 296297
performance, 294295
polyfills, 292
realistic animation, 295296
transform matrix, 293
transforms, 292
transitions, 293294
transitions vs. animations, 294295
twelve principles of animation, 295296
updated lists of animatable properties, 91
I N DE X
S
scale() function, 2223, 52
scaling
modal window to final size, 236237, 239240
shrinking modal windows, 237240
transform for squash and stretch animation,
153158
using scale() function, 2223
secondary action, 195196
shrinking modal windows, 237240
skeuomorphic realism, 211, 289
skewing objects, 24
sliding
content block while changing opacity, 280
modal window as it becomes opaque, 232234,
239240
modifying content block opacity and scale while,
275282
off-canvas sidebar on/off canvas, 259268
smoothing animation for, 98100
submenu offscreen, 221222
using CSS positioning in, 9698
smoothing animation, 98100
solid drawing, 206207
squash and stretch, 149158
stacking contexts, 3031
staging, 164167
Stanchfield, Walt, 208
starting animations, 100, 106
states, animation, 142
step functions, 6971
straight-ahead action, 168
syntax
adding values in step functions, 69
transitioning multiple properties, 62, 81
using asterisk in properties, 47
writing multiple transforms, 2930
T
:target hack, 231
Thomas, Frank, 148
3-D CSS transforms, 3352
about, 3334
303
304
I N DE X
transforms (continued)
setting fixed point for object, 1620
transform rendering model for 2- and 3-D,
3033
used during arcing of bouncing ball, 194
working with, 5556
transition-* properties
checking mismatched vendor prefixes in, 68
setting values on, 92
transition-delay property, 7981
transition-duration property, 6668
transition-property, 6265
transition-timing-function, 6878
using shorthand transition property, 81
transitionend event values, 84
transitions, 5792. See also background color
transitions; transition-* properties
about, 56, 5758, 92
accelerating and decelerating, 6878
adding multiple transitions to elements, 6263,
81, 92
adding to background color, 217
animatable property resources, 294
animations vs., 57, 94, 141145, 217, 294
browser support for, 58, 92
CSS animatable properties for, 8991
DOM events generated by, 8488
example code for, 5962, 6365
resources on, 293294
shorthand method for, 81
starting and reversing, 8283
transition event resources, 293
types of animation for, 67
using with drop-down menu, 218223
translate() function, 2122, 52
trends in animation, 211, 289
triggering animation play with buttons, 123125
twelve principles of animation
about, 209210
additional principles, 208209
anticipation, 158164
appeal, 207208
arcs, 182195
exaggeration, 197206
follow-through and overlapping action, 168181
overview, 148149
practicing animation principles, 290
resources on, 295296
secondary action, 195196
slow in and slow out, 182
solid drawing, 206207
squash and stretch, 149158
staging, 164167
straight-ahead and pose-to-pose actions, 168
timing, 196197
2-D CSS transforms, 1433
browser support for, 7, 8
coordinate space for, 12
distinguishing functions in 3-D and, 52
functions for, 2128
IE support for, 13
properties for, 1620, 55
rotating box, 1416
3-D rotations vs., 3637
transform rendering model for, 3033
U
underscore hack, 216
user interface design
animation as guide in, 289
animation in, 208, 209, 289
resources on, 296
user expectations of forward and reverse
transitions, 83
V
values
adding for step functions, 69
applying to completed animations, 128
overriding preserve-3d, 40
resetting inside keyframes, 100
setting for transition-* properties, 92
using different values for multiple animation
properties, 100
visibility, 3-D backface, 4351
visual formatting model, resources on, 293
W
webkit vendor prefix
browser support and, 13, 15
checking mismatches in transition-*
properties, 68
transitions and, 58
webkitTransitionEnd event, 84
website design
about transitions, 56
animation in, 35, 208, 209, 289
choosing browsers to support, 287
hierarchy of needs in, 23, 288
progressive enhancement in, 243, 259, 288289
trends in, 211, 289