CSS Animations

CSS Animations

CSS Animations

When building a css animation you’ll need to know to essential keywords:

  1. @keyframes

  2. animation

The first one is used to define how an animation behaves over time and the second one is used to reference the keyframes that we create.

Let’s assume that we have a box and we need to shift it to the right of the page by 100px from the original position.

.box {
    width: 100px;
    height: 100px;
    background-color: red;
    -webkit-animation: box-100px 4s; /* Safari 4.0 - 8.0 */
    animation: box-100px 4s;
}

Since animation: box-100px 4s; have two values you can already assume what is happening there.

Yes, That’s right: animation: box-100px 4s; can also be written like:

.box {
    ...
    animation-name: box-100px;
    animation-duration: box-100px;
}

@keyframes box-100px {
    from {
        background-color: blue;
    }
    to {
        background-color: red;
        transform: translate(100px, 0);
    }
}

So both of this adaptations are equally true. However consider using the second version since it’s better suited for cases when other developers are working with your code.

In the last part of our code you could find out that there we used two new keywords:

  1. from

  2. to

The first keyword is defining how our animation will look at the beginning and the second one is changing the box until animation ends. So, depending on what we have specified in the “to” clause the animation will change progressively until it reaches that point where transform: translate(100px, 0); is fulfilled.

But, suppose we receive a task that affirms when our animation is at 50% duration then we demand to change the background-color to yellow:

@keyframes box-100px {
   0% {
      background-color: blue; 
   }
   50% {
      background-color: yellow;
   }
   100% {
      background-color: red;
      transform: translate(100px, 0);
   }
}

Oh but… , something new again. Yes, you can also use percentages to apply style to elements at particular times in you animtions.

 

So, essential animations ca easily be build with just a few lines of code.

Here is the code for this post:

<iframe style="width: 100%; height: 300px; border: 0; border-radius: 4px; overflow: hidden;" src="https://codesandbox.io/embed/43992opzj4?module=%2Fstyle.css" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

Related Posts