There are currently two ways to animate things with CSS:
- Keyframe Animations
Each technique has similarities and differences. Here’s how they work.
Transitions work by morphing a property from one value to another when the transition is triggered.
Here is a simple example (hover your mouse over the box to trigger the transition):
There are several ways to trigger a transition. The most common way is with the :hover pseudo-class (which you saw in the example above), but others include:
- page load
- media queries
- device orientation
(By the way, there’s a great article by Louis Lazaris demonstrating some examples of these techniques)
In all cases, a user performs some action, which sets our transition in motion. You can adjust many properties of the transition, like the delay or timing, but all transitions must have a beginning and an end.
Keyframe animations are similar to transitions, in that they can be used to morph properties from one value to another, but they differ in how they are defined. You define them by identifying the keyframes that make up your animation and giving that set of keyframes a name. Then, you can invoke those keyframes anywhere you want, using CSS selectors. Let’s look at an example:
As you can see, we’ve defined our “pulse” keyframes, and applied it to several elements.
Which is Better?
Both have their strengths and weaknesses. Here are a few of the main benefits I’ve found for each option:
Benefits of Transition:
- Slightly better browser support (compare transitions to animations)
- Familiar syntax
- Easy to manipulate in Firebug/Devtools
Benefits of Keyframes:
- More granular timing control
- Easy to mix and match properties (one keyframe definition can animate color and opacity, and size, etc.)
- More animation options (infinite, alternate, etc.)
- Keeps code DRY
Personally, I feel like animations with keyframes are more powerful, but it really comes down to your specific application (for example, I chose to use transitions in AnchorJS and keyframe animations for my Flying Toasters).
Finally, one property that is often confused with these animation techniques is transform. While transform is new and can do some neat things (like rotate, scale, translate, etc), it doesn’t animate anything. It’s a typical css property like font color or opacity.