DEV Community

Mohammed Shaikh
Mohammed Shaikh

Posted on

Animation with vanilla css

A map shaking

Animation makes our app look a little exciting and it is very easy to do it with plain css. The first thing we need is the @keyframes css keyword. what that keyword does is that it lets us control an element on the dom. We can tell the dom to do a certain action in exact intervals. We measure intervals in percentages.

  @keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, -2px) rotate(-1deg); }
  }
Enter fullscreen mode Exit fullscreen mode

The whole animation is considered 100%.If the change we want should happen in the beginning we put it at 0%. If we want it to be halfway through the animation, we put it at 50% and at 100%, if that is the last thing we want done. We started from the beginning(0%) and told the element to move 1px on the x-axis and 1px on y-axis and rotate 0 deg and so on and so forth.

The next thing we have to do is bind the function to an element.

#map:hover {
    /* Start the shake animation and make the animation last for 0.5 seconds */
    animation: shake 0.5s;

    /* When the animation is finished, start again */
    animation-iteration-count: infinite;
  }
Enter fullscreen mode Exit fullscreen mode

I put an event listener on the map, so when someone hovers over it this css blocks get triggered. animation: shake 0.5s; There are three arguments on this line, first is the animation keyword, then it is the name of the function we wrote above and the length of how long it should run.A thing to note, the percentages are of the time we mention in this command. 50% in keyframes is 50% of 0.5s in our example.

There are many things possible with @keyframes. We could even change the colors programmatically

@keyframes colorChange {
  0%   {background-color: red;}
  25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}
Enter fullscreen mode Exit fullscreen mode

We can use negative numbers to make it look like the animation was already playing and if leave out 0% and 100% it will automatically make those two points equal to the beginning state of the element and it will start and end the animation at the same state

Yay!! Now you know how to add animation using css. Hopefully it will bring as much joy to your projects as it did to mine

Top comments (0)