How To Create Animations with CSS

CSS animations allow you to add dynamic effects to your web pages. You can create animations using keyframes and the animation property.

Keyframes

Keyframes define the stages of an animation. Here’s an example:

@keyframes slidein {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

Using the Animation Property

The animation property applies the animation to an element.

.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  animation: slidein 2s ease-in-out;
}

Multiple Animations

You can also apply multiple animations to an element by separating them with commas.

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.box {
  animation: slidein 2s ease-in-out, fadein 2s ease-in-out;
}

Animation Shorthand

The animation property is a shorthand for several sub-properties: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state.

.box {
  animation: slidein 2s ease-in-out 1s infinite alternate both;
}