DEV Community

Cover image for Using CSS Animation
Kenneth Lum
Kenneth Lum

Posted on • Updated on

Using CSS Animation

We used CSS transition in the past, and sometimes, we may need to use setTimeout() to deal with multistep animations, or if we add a new element, and we want to transition it, because it first have to have an opacity of 0, and then transition to 1.

CSS Animation is ready for prime time. It can be used on most modern browsers.

Here is one demo: https://jsfiddle.net/KennethKinLum/q6gjhatd/

To be able to see it in a bigger window, we can use codesandbox.io: https://codesandbox.io/s/gifted-wozniak-wf09y and the full window page: https://wf09y.codesandbox.io/ or https://wf09y.csb.app/

Basically, we can just look at:

 document.querySelector("#btn").addEventListener("click", ev => {
   const newRow = document.createElement("tr");

   addNewRow(tableElement, newRow);
   newRow.classList.add("new-row");
 });
Enter fullscreen mode Exit fullscreen mode

It is adding a new class new-row to the row, and the class has this CSS Animation definitions:

.new-row {
  animation: 1.2s forwards fade_in_and_settle;
}

@keyframes fade_in_and_settle {
  0% {
    opacity: 0;
    background: #fff;
  }

  50% {
    opacity: 1;
    background: #ff0;
  }

  100% {
    opacity: 1;
    background: #fff;
  }
}
Enter fullscreen mode Exit fullscreen mode

It is just stating, at the very beginning (0%), how should the CSS style be, and also, at 50%, and at 100%.

The default behavior is, after the animation is complete, then the effect is removed and it is "reverted" back to before the animation. Sometimes we want that behavior, and sometimes we want the effect to "stay" at its final state, even after the animation. Then the keyword forwards can to be used, like the following:

.new-row {
  animation: 1.2s forwards fade_in_and_settle;
}
Enter fullscreen mode Exit fullscreen mode

Without it, it would be back to before, and in this case, it is actually equally acceptable.

There are several other properties that can be useful. Refer to the MDN docs or CSS: The Definitive Guide, 4th Ed, Chapter 18 for more info. Some that are useful are:

  • iteration count: it can be 1, 2, 3, or infinite, meaning repeat the animation and don't stop it. The ReactJS spinning logo is done by infinite to make it always spinning.
  • direction: it can be normal, reverse, and alternate. For example, if the requirement is to make the background go from green to red and back to green, and repeat, it can be alternate together with infinite above.
  • timing function: it can be ease, linear, ease-in, ease-out, and even defined by our own cubic-bezier function. For more information, refer to the docs mentioned above.

Top comments (0)