CSS @keyframes Rule

CSS @keyframes rule is used to define CSS styles at various intermediate points in an animation sequence. Unlike the transition property, the @keyframes at-rule provides flexibility to define CSS styling as many intermediate points as we want.

The beginning of the animation is specified using ‘from’ or 0% and the ending is specified using ‘to’ or 100%. You can define CSS styling at any intermediate point for example, ‘30%’, ‘50%’, ‘70%’ etc.

The @keyframes rule has the below syntax:

@keyframes your-animation-name{
   your-animation-selector{
      CSS styles
   }
} 

After defining your keyframe, you have to pass it to the animation property. In this example, we will pass three parameters to the animation property:

  • Keyframe name – Specifies the keyframe name that you have created
  • Animation duration – Specifies how much time the animation takes to complete
  • Animation iteration count – Specifies how many time the animation should be played

See the implementation in the below example:

Example:

@keyframes moveRight{
  from{
     left: 10px;
  }
  to{
     left: 200px;
  }
}

div{
  animation: moveRight 6s infinite;
}

The @keyframes rule allows us to add CSS styling at any intermediate point during the animation. These animation points can be selected using the percentage value(%) for example, ‘30%’, ‘50%’, ‘70%’, etc.

In the example below, we change the background color of the <div> element to springgreen once the animation reaches 50%.

Example:

@keyframes moveRight{
  from{
     left: 10px;
  }
  50%{
     background-color: springgreen; 
  }
  to{
     left: 200px;
  }
}

div{
  animation: moveRight 6s infinite;
}

Note: CSS styles defined with !important rule are completely ignored by the @keyframes.


CSS Syntax

The @keyframes at-rule has the following syntax:

@keyframes keyframe-name{ keyframe-selector{ css-styles } }

Property Values

The @keyframes at-rule accepts the following values:

keyframe-nameName of the keyframe you want to create. You can choose any name you want. It is used by the animation property.
keyframe-selectorSelects intermediate points during an animation. There are two inbuilt selectors:
from(same as 0%) – Specifies the beginning of an animation
to(same as 100%) – Specifies the end of the animation
You can choose any value between 0-100% to select any particular point during the animation.
A single keyframe can have any number of keyframe selectors.
css-stylesAny valid CSS style(s).

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment