Chapter 2. Animating with CSS

You may find working with SVG code feels very familiar, mostly because an SVG has a DOM, just like standard HTML markup. This is hugely valuable when working with CSS animations, as manipulating markup with CSS is already a very comfortable process for most frontend developers.

For a very brief review, let’s first establish that a CSS animation is created by defining two parameters. First, there are the keyframes themselves:

@keyframes animation-name-you-pick {
  0% {
   background: blue;
   transform: translateX(0);
 }
  50% {
   background: purple;
   transform: translateX(50px);
 }
  100% {
   background: red;
   transform: translateX(100px);
 }
}

Keyframe Syntax Hint

You can also define from and to instead of percentages. If you declare nothing in either the initial keyframe or the ending keyframe, the animation will use the default or declared properties on the element. It may be worth double-checking your work in all browsers if you do remove them, though, due to strange and inconsistent browser bugs.

After you define the keyframe values, you have two options for animation syntax declaration. Here’s an example of the long form, with each declaration defined separately:

.ball {
  animation-name: animation-name-you-pick;
  animation-duration: 2s;
  animation-delay: 2s;
  animation-iteration-count: 3;
  animation-direction: alternate;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}

And here’s the shorthand (my preferred method, ...

Get SVG Animations now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.