Multiple animations
In this chapter we’ll be looking at how we can make use of multiple sets of keyframes running at the same time.
Traffic lights
There are times when we want multiple animations on a page to stay in sync, but at the same time each animation has its own timing. A good example that illustrates this is traffic lights
Here we have a simple (UK-style) traffic light pattern:
We have three lights, each with their own pattern of being off and on. We can create this by giving each light their own animation.
.red {
animation: red 10s linear infinite;
}
.amber {
animation: amber 10s linear infinite;
}
.green {
animation: green 10s linear infinite;
}
We have three animations, one for each light. Each animation lasts the same length of time so that when they loop, they won’t go out of sync. Next we need to plan the keyframes.
When creating this example I found it helpful to think of the lights as a grid. The animation happens from left to right, with each light being on or off at certain times.
The grid is divided up into 5 columns. This means that we can deal with “chunks” of 20% and create sets of keyframes from these chunks.
Taking each light one at a time, we can start with the red light. It would be on for the first and second chunks, then off for the rest of the animation. The resulting keyframes
:
@keyframes red {
0% {
background: black;
}
2%, 40% {
background-color: red;
}
42%, 100% {
background: black;
}
}
I’ve added a 2% gap at the beginning and had the third part of the animation begin at 42% as this adds a little bit of a fade to the way the traffic light appears. It’s the subtle stuff that makes all the difference.
With the red light done, we look at the amber light on the grid.
The amber light is off at the beginning, on for one chunk, then off for two chunks, and finally on again. The keyframes
for this light:
@keyframes amber {
0%, 20% {
background: black;
}
22%, 40% {
background: #FF7E00;
}
42%, 80% {
background: black;
}
82%, 100% {
background: #FF7E00;
}
}
Lastly, the green light. This light is off for the first two chunks, then on for two, and finally off for one.
@keyframes green {
0%, 40% {
background: black;
}
42%, 80% {
background: green;
}
82%, 100% {
background: black;
}
}
We can put it all together and see it in action.
Further reading
For more reading on the subject of keyframe
syntax, do check out CSS tricks article on the subject.
Homework
Today’s homework is a challenge. The traffic light example might look strange to you as it follows the UK pattern.
Can you start with the traffic light example and change it so that it works more like traffic lights in the USA or elsewhere?