Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
CSS lets you create animations using the @keyframes rule. It has the following syntax:
@keyframes <animation_name> {
from {
<style_rule_1>;
<style_rule_2>;
/* . . . */
}
to {
<style_rule_1>;
<style_rule_2>;
/* . . . */
}
}For instance, in the following example, the animation is named change-bg-color, and it changes the background-color from white to darkviolet:
@keyframes change-bg-color {
from {
background-color: white;
}
to {
background-color: darkviolet;
}
}And next, to apply this animation, specify the animation-name and animation-duration properties:
div {
animation-name: change-bg-color;
animation-duration: 4s;
}The animation-duration determines how long it takes for the animation to finish. In this example, the animation completes in 1 second:
div {
animation-name: change-bg-color;
animation-duration: 1s;
}Animation Duration
Compare the animations at 0.5x, 1x, and 2x speed.
Instead of using the keywords from and to, it is also possible to use percentage values when setting keyframes. This allows you to create multi-step animations:
@keyframes change-bg-color {
0% {
background-color: white;
}
25% {
background-color: bisque;
}
50% {
background-color: crimson;
}
100% {
background-color: darkviolet;
}
}Take a look at this example:
<div class="four-kf-animation">4 Keyframes Animation</div>@keyframes change-bg-color-4kf {
0% {
background-color: #ffffff;
}
25% {
background-color: #fff4e8;
}
50% {
background-color: #e65a63;
}
100% {
background-color: #5b2a86;
}
}
.four-kf-animation {
padding: 10px;
margin: auto;
border: 2px solid darkviolet;
border-radius: 10px;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
"Lucida Sans", Arial, sans-serif;
color: darkviolet;
width: 200px;
animation-name: change-bg-color-4kf;
animation-duration: 5s;
}Just like transitions, animation allows you to define a animation-timing-function, which works exactly the same as their transition counterparts.
div {
/* . . . */
animation-name: change-bg-color;
animation-duration: 4s;
animation-timing-function: ease-in-out;
}Animation Timing Function
By default, the animation starts playing the moment the element is loaded. Using animation-delay, you can decide how long to wait before starting an animation.
div {
/* . . . */
animation-name: change-bg-color;
animation-duration: 4s;
animation-timing-function: ease-in-out;
animation-delay: 2s;
}<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="two-kf-animation">2 Keyframes Animation</div> <div class="four-kf-animation">4 Keyframes Animation</div> </body> </html>