๐ŸŽ“ A1Learner
๐Ÿ”

CSS Animations

An animation runs a set of style steps on an element over time. A @keyframes block names the steps, and animation properties attach them to an element.

A pulsing image

The keyframes fade the image from full opacity to 0.4. The animation rule runs those steps on the image, once per second, without end.

@keyframes pulse {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.4;
  }
}
.pic {
  animation: pulse 1s infinite;
}

Steps written as percentages

Percentage steps give a midpoint as well as a start and an end. The box background moves through red, then yellow, then blue.

@keyframes shade {
  0% {
    background-color: red;
  }
  50% {
    background-color: yellow;
  }
  100% {
    background-color: blue;
  }
}
.box {
  animation: shade 2s infinite;
}

Example

@keyframes pulse {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.4;
  }
}
@keyframes shade {
  0% {
    background-color: red;
  }
  50% {
    background-color: yellow;
  }
  100% {
    background-color: blue;
  }
}
.pic {
  animation: pulse 1s infinite;
}
.box {
  animation: shade 2s infinite;
}

Key points

  • from and to in a @keyframes block are the 0% and 100% steps.
  • animation-name names the @keyframes block an element runs.
  • animation-duration sets how long one run of the steps takes.
  • animation-iteration-count sets how many times the steps repeat.
  • animation-direction can run steps in reverse or in alternating directions.
  • animation-fill-mode sets the styles an element keeps before a run or after it.

In this example, the first @keyframes block fades opacity from 1 down to 0.4. The second block moves a background colour through three percentage steps. The image runs the pulse steps every second. The box runs the shade steps every two seconds, and both run without end.

Note

While an animation runs, it overrides the plain value of the property it animates.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does a @keyframes block hold?