CSS @keyframes rule
The CSS @keyframes
rule is used to define the intermediate steps or “keyframes” in a CSS animation. It allows you to specify how an element should be styled at various points during the animation’s duration. The @keyframes
rule is a crucial part of CSS animations, enabling you to create dynamic and visually appealing effects on web elements.
The syntax for creating a @keyframes
rule is as follows:
@keyframes animationName {
/* Define keyframes at different percentages of the animation duration */
0% {
/* CSS properties at the start of the animation */
}
50% {
/* CSS properties halfway through the animation */
}
100% {
/* CSS properties at the end of the animation */
}
}
animationName
: The name you give to the animation, which you will later use in theanimation-name
property to apply the animation to an element.
Inside the @keyframes
rule, you define various keyframes at different percentages of the animation’s duration. The percentages range from 0%
to 100%
, indicating the animation’s starting point to its ending point.
At each keyframe, you specify the CSS properties that should be applied to the element. These properties will interpolate between the keyframes, creating a smooth transition between the defined states.
Example:
@keyframes fadeInOut {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.element {
animation-name: fadeInOut;
animation-duration: 2s;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}
In this example, we create a @keyframes
rule named fadeInOut
, which defines three keyframes at 0%
, 50%
, and 100%
. The element with the class .element
will use the fadeInOut
animation, causing it to fade in from transparent to fully opaque at the halfway point and then fade out again.
By utilizing the @keyframes
rule, you can craft complex and interactive animations in CSS without the need for JavaScript. CSS animations provide a way to enhance the user experience and bring elements to life on a webpage.