css
  1. css-keyframes

CSS @keyframes

  • The @keyframes rule in CSS is used to create animations and define the keyframes that make up those animations.
  • It allows you to specify how an element should move or transform over time.

Syntax

@keyframes animation-name {
  0% {
    /* CSS properties at the start of the animation */
  }
  50% {
    /* CSS properties at the halfway point of the animation */
  }
  100% {
    /* CSS properties at the end of the animation */
  }
}

Example

Here is an example of using the @keyframes rule to create a simple animation:

/* Define the @keyframes rule */
@keyframes example-animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1);
  }
}

/* Apply the animation to an element */
.box {
  animation: example-animation 1s ease infinite;
}
Try Playground

Here we define an animation called example-animation that scales an element up to 1.5 times its original size and then back down to its original size. We apply the animation to an element with the class .box, and set the animation to run for 1 second, with an easing function of ease, and to run indefinitely.

Explanation

The @keyframes rule allows you to define the different states or keyframes of animation. In our example, we used three keyframes - one at the beginning, one at the halfway point, and one at the end of the animation. At each keyframe, we specified the CSS properties that should be applied to the element.

We then applied the animation to an element using the animation property. In our case, we set the animation to run for 1 second, with an easing function of ease, and to run indefinitely using the infinite keyword.

Use

The @keyframes rule can be used to create a variety of animations, from simple transitions like the one in our example above, to more complex animations that incorporate multiple keyframes and properties.

Important Points

  • The @keyframes rule is used to define the different states of an animation.
  • You can specify multiple keyframes to create more complex animations.
  • Use the animation property to apply the animation to an element.
  • You can set a variety of options for the animation, such as duration, timing function, and iteration count.

Summary

The @keyframes rule in CSS is a powerful tool for creating animations that add visual interest and interactivity to your web pages. Using keyframes, you can define the different states of your animation and control how an element moves or transforms over time. With its versatile syntax and wide range of options, @keyframes is a must-know for any web developer looking to create dynamic and engaging websites.

Published on: