For multi-stage CSS animations, you can create CSS @keyframes
. Keyframes allow you to define multiple animation points, called a keyframe, to define more complex animations.
In this example, we'll make a basic background animation that cycles between all colors.
@keyframes rainbow-background {
0% { background-color: #ff0000; }
8.333% { background-color: #ff8000; }
16.667% { background-color: #ffff00; }
25.000% { background-color: #80ff00; }
33.333% { background-color: #00ff00; }
41.667% { background-color: #00ff80; }
50.000% { background-color: #00ffff; }
58.333% { background-color: #0080ff; }
66.667% { background-color: #0000ff; }
75.000% { background-color: #8000ff; }
83.333% { background-color: #ff00ff; }
91.667% { background-color: #ff0080; }
100.00% { background-color: #ff0000; }
}
.RainbowBackground {
animation: rainbow-background 5s infinite;
}
There's a few different things to note here. First, the actual @keyframes
syntax.
@keyframes rainbow-background{
This sets the name of the animation to rainbow-background
.
0% { background-color: #ff0000; }
This is the definition for a keyframe within the animation. The first part, the 0%
in the case, defines where the keyframe is during the animation. The 0%
implies it is 0% of the total animation time from the beginning.
The animation will automatically transition between keyframes. So, by setting the next background color at 8.333%
, the animation will smoothly take 8.333% of the time to transition between those keyframes.
.RainbowBackground {
animation: rainbow-background 5s infinite;
}
This code attaches our animation to all elements which have the .RainbowBackground
class.
The actual animation property takes the following arguments.
rainbow-background
-2s
would start the animation 2 seconds into its loop.ease
, where the animation starts slow, gets faster and ends slow.In this particular example, both the 0%
and 100%
keyframes specify { background-color: #ff0000; }
. Wherever two or more keyframes share a state, one may specify them in a single statement. In this case, the two 0%
and 100%
lines could be replaced with this single line:
0%, 100% { background-color: #ff0000; }
For older WebKit-based browsers, you'll need to use the vendor prefix on both the @keyframes
declaration and the animation
property, like so:
@-webkit-keyframes{}
-webkit-animation: ...