Skip to content

Animations

When an element changes states, whether it’s through a pseudo-class like :hover, or with a change from some JavaScript, we can use transitions ease the change from one of those states to the other.

Sometimes, we might want more control over the in-between parts instead of only the start or the end, or we might want to trigger something and then have it stay in the new state.

We can do that using CSS animations.

Before we can use an animation, we have to create one. To do that, we use the another CSS at-rule: @keyframes.

Inside the keyframes declaration, we create keyframes using percentages, like this:

@keyframes color-shift {
0% {
background-color: purple;
}
25% {
background-color: orange;
}
50% {
background-color: dodgerblue;
}
100% {
background-color: cyan;
}
}

As you can see, unlike a transition where we go from a start point to an end point, here we can control everything along the middle as well.

Simply creating an animation doesn’t do much though, we need to use that animation as well!

.shifting-bg {
animation-name: color-shift;
animation-duration: 10s;
}

We also have an animation shorthand, which is a lot like the transition shorthand, but it does require the name of the animation as well as a duration.

.shifting-bg {
animation: color-shift 10s;
}

There are a few other properties with animations:

  • animation-name
  • animation-duration
  • animation-timing-function
  • animation-delay
  • animation-iteration-count
  • animation-direction
  • animation-fill-mode
  • animation-play-state
  • animation-timeline (relatively new)