Skip to main content

CSS Animations

What are CSS Animations?​

An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must first specify some keyframes for the animation.

Keyframes hold what styles the element will have at certain times.

The @keyframes Rule​

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times. To get an animation to work, you must bind the animation to an element.

/* The animation code */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}

/* The element to apply the animation to */
div{
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
http://127.0.0.1:5500/index.html

Hello World!

The animation-duration property defines how long an animation should take to complete. If the animation-duration property is not specified, no animation will occur, because the default value is 0s (0 seconds). In the example above we have specified when the style will change by using the keywords "from" and "to" (which represents 0% (start) and 100% (complete)). It is also possible to use percent. By using percent, you can add as many style changes as you like.

Delay an Animation​

The animation-delay property specifies a delay for the start of an animation.

div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-delay: 2s;
}
http://127.0.0.1:5500/index.html

Hello World!

Times animation should run

The animation-iteration-count property specifies the number of times an animation should run.

div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
}
http://127.0.0.1:5500/index.html

Hello World!

Direction of the animation

The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles.

The animation-direction property can have the following values:

  • normal - The animation is played as normal (forwards). This is default
  • reverse - The animation is played in reverse direction (backwards)
  • alternate - The animation is played forwards first, then backwards
  • alternate-reverse - The animation is played backwards first, then forwards
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-direction: reverse;
}
http://127.0.0.1:5500/index.html

Hello World!