Frontend Software Engineer Hire

CSS Animation Basics

To animate an element, it's easiest to think of it in two states.

  1. The element before it's animation is triggered
  2. The element after it's animation is triggered.

Step 1: Define the change (but not the animation, yet)

Let's say we have a button with HTML like this: <button class="chameleon">Hover Here</button>

We could create some css to describe the button's color at rest, as well as when it's being hovered-over by the mouse:

.chameleon {
  background-color: #A727FF;
}

.chameleon:hover {
  background-color: #4E92FF;
}

The button changes color, but the change happens instantly. To make it more gradual, we need to define what we'd like to change and how using CSS.

Step 2: Define the animation

Now that we've declared what we want the button to look like when it's been hovered-over, we just need to declare that we'd like that change to happen gradually. This is done on the first css selector, .chameleon

.chameleon {
  background-color: #A727FF;
  transition: background-color .5s;
}

.chameleon:hover {
  background-color: #4E92FF;
}

Notice the transition property defines the property you'd like to animate, and how long you want it to take to reach it's target. In this case, we want to animate background-color over a half second.

Reference

-webkit-transition: all .25s ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier(<number>,<number>,<number>,<number>);
   -moz-transition: all .25s ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier(<number>,<number>,<number>,<number>);
    -ms-transition: all .25s ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier(<number>,<number>,<number>,<number>);
     -o-transition: all .25s ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier(<number>,<number>,<number>,<number>);
        transition: all .25s ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier(<number>,<number>,<number>,<number>);

-webkit-transition: all .25s;
   -moz-transition: all .25s;
    -ms-transition: all .25s;
     -o-transition: all .25s;
        transition: all .25s;

-webkit-transform: scale(2);
   -moz-transform: scale(2);
    -ms-transform: scale(2);
     -o-transform: scale(2);
        transform: scale(2);

-webkit-transform: scale(1);
   -moz-transform: scale(1);
    -ms-transform: scale(1);
     -o-transform: scale(1);
        transform: scale(1);