cssKeyframe Animations

This entire section is optional. If you are interested in learning the basics of CSS animation, feel free to dive in, but it is not required for this course or any of your projects.

Basics

Using animation in CSS requires two steps:

  1. First, you must apply a set of animation properties or the animation shorthand, including a name for your animation.
  2. Then, you need to breakdown the animation sequence using CSS keyframes.

Let’s look at a very basic example of a CSS animation.

The CSS for each step to create this animation is detailed below.

Step one

div {
  /* The basic styles for the element */
  background-color: #A2F1C1;
  height: 60px;
  /* Animation specific styles */
  animation: slideIn 4s linear infinite;
  transform-origin: left center;
}

The animation shorthand property here includes:

Additionally, since this animation uses CSS transformations, an origin for the transformation is set using the transform-origin property.

Step two

The above code has no effect unless an @keyframes rule with a matching name exists. In this case, that code looks like this:

@keyframes slideIn {
  from {
    transform: scaleX(0);
  }

  to {
    transform: scaleX(1);
  }
}

Two important things to note about keyframes:

Accessibility and animations

Some individuals have vestibular disorders and may experience nausea or other signs of physical discomfort when web pages include animations. Users can specify in their operating system/device settings if they prefer to experience things with less/reduced motion and, since you don’t want your designs to make someone physically ill, you should always write your CSS to respect those settings.

To do this, you can use a media query and the prefers-reduced-motion feature. For the demo above, it looks like this:

@media (prefers-reduced-motion) {
  div {
    animation: none;
  }
}

For roughly the last year, browsers have been supporting this media feature; see Can I Use for specific details.

More resources