How to use CSS Animation with examples

How to use CSS Animation with examples

Improve the user experience feeling with animations.

I continue fixing my CSS weakness and today is time for the CSS Animation.

CSS helps us create animation using the keyword @keyframes, it helps to set the initial state for properties and the amount of time it will get during the animation.

We change the size, color, size, visibility, and more properties.

Create my keyframe animation

The keyframes require the name and using from to help us to scope from begin to end which properties are modified.

For example, the animation myanimation, change border radius from 0 to 50%.

@keyframes myanimation {
    from {
        border-radius:0px
    }
    to {
        border-radius: 50%;
    }
}

DEMO

Connect my keyframes with an element

My element needs to know the animation-name and animation-duration.

animation-name: myanimation;
animation-duration: 3s;

DEMO

Another way to write your animation is with % instead of from to, because it is flexible to future changes.

DEMO

Others properties are animation-delay and animation-iteration-count, these 2 are not required but help us to create nice effects.

  • animation-delay: start the animation after delay;

  • animation-iteration-count: set how many times is the animation run but by default 1, it can be changed by other numbers values or infinite to not stop.

Sometimes we want to start elements with the keyframe state for these cases use animation-fill-mode with the value backwards.

animation-fill-mode: backwards;

If you want to keep the last element state use option fowards.

animation-fill-mode: fowards;

For both situations the use both keyword.

animation-fill-mode: both;

That's it!

This is a quick overview with animation in CSS, you can play with it and build great animation in css like that:

FINAL DEMO If you enjoyed this post, share it!

Image thanks Gensa Hub.