How to animate elements in CSS

CSS animations allow you to animate most of the HTML elements without using JavaScript or any other language such as Flash, etc.

The @keyframes rule

The @keyframes at-rule is used to define the behavior of one cycle of a CSS animation.

To define an animation you have to do the following:

  • Start with the @keyframes rule.
  • The rule consists of the keyword “@keyframes“ followed by an identifier giving a name for the animation (referenced below using animation-name property)
  • This is then followed by a set of style rules.
  • The animation can then be applied to an element by using the identifier as a value for the animation-name property of the element.

Syntax

The syntax and example to make a CSS animation are as follows:

@keyframes example-animation-name {
/* style rules written here*/
}
/* Apply it to an element */
element {
/* CSS code written here*/
animation-name: example-animation-name;
}

Example

In the example below, the sample animation binds to the <div> element using the animation-name property. The animation will last for 5 seconds due to the animation-duration property. We observe a gradual color change in the background color of the <div> element from blue to yellow as styled in the @keyframes rule. The animation stops with red background color as specified by the background-color property used inside the <div> element.

More on the @keyframes rule

In the example above, we used the keywords from and to in order to specify when the style will change. It is also possible to use percent where 0% represents the start of the animation and 100% represents the completion state of the animation. By using percent, we can add as many style changes as we like.

Example

In the example below, the animation binds as mentioned before. We add the animation-delay property which waits for two seconds before starting the animation. Inside the @keyframes rule, we change both the position and the background color of the <div> element at 25% complete, 50% complete, 75% complete and finally when 100% complete.

Copyright ©2024 Educative, Inc. All rights reserved