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:

Source: http://codepen.io/donovanh/pen/ogRRdR?editors=010

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.

  1. .red {
  2. animation: red 10s linear infinite;
  3. }
  4. .amber {
  5. animation: amber 10s linear infinite;
  6. }
  7. .green {
  8. animation: green 10s linear infinite;
  9. }

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.

Multiple animations - 图2

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:

  1. @keyframes red {
  2. 0% {
  3. background: black;
  4. }
  5. 2%, 40% {
  6. background-color: red;
  7. }
  8. 42%, 100% {
  9. background: black;
  10. }
  11. }

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:

  1. @keyframes amber {
  2. 0%, 20% {
  3. background: black;
  4. }
  5. 22%, 40% {
  6. background: #FF7E00;
  7. }
  8. 42%, 80% {
  9. background: black;
  10. }
  11. 82%, 100% {
  12. background: #FF7E00;
  13. }
  14. }

Lastly, the green light. This light is off for the first two chunks, then on for two, and finally off for one.

  1. @keyframes green {
  2. 0%, 40% {
  3. background: black;
  4. }
  5. 42%, 80% {
  6. background: green;
  7. }
  8. 82%, 100% {
  9. background: black;
  10. }
  11. }

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?