What are CSS keyframes?
During a CSS animation, the styling of an element can change multiple times. Thus, whenever you're creating an animation, you need to define certain points called CSS keyframes at which the element will change styling.
To specify the code of the animation, you need to use the CSS @keyframes
rule:
@keyframes animate {
0% {top: 0px; left: 0px; background: blue;}
25% {top: 0px; left: 100px; background: green;}
50% {top: 100px; left: 100px; background: red;}
75% {top: 100px; left: 0px; background: black;}
100% {top: 0px; left: 0px; background: grey;}
}
The syntax for keyframes in CSS
The syntax requirements for using the CSS @keyframes
rule are as follows:
@keyframes animationname {keyframe {css-styles;}}
Value | Description |
---|---|
animationname | The name of an animation |
keyframe | The point of the animation duration at which the specified change occurs |
css-styles | CSS style properties |
Animations are normally gradual transitions from one set of CSS styles to another. You can specify CSS keyframes in two ways:
- using percentages (
0%
for the starting and100%
for the ending point of the animation):
/* Opera, Chrome, Safari */
@-webkit-keyframes animate {
0% {top: 0px; background: green; width: 100px;}
100% {top: 200px; background: black; width: 300px;}
}
/* Standard syntax */
@keyframes animate {
0% {top: 0px; background: green; width: 100px;}
100% {top: 200px; background: black; width: 300px;}
}
- using keywords (
from
for the starting andto
for the ending point of the animation):
/* Opera, Chrome, Safari */
@-webkit-keyframes animate {
from {bottom: -100px;}
to {bottom: 500px;}
}
/* Standard syntax */
@keyframes animate {
from {bottom: -100px;}
to {bottom: 500px;}
}
To ensure optimal browser support for your CSS keyframes, you should define both 0% and 100% selectors:
/* Chrome, Safari, Opera */
@-webkit-keyframes animate {
0% {top: 0px;}
25% {top: 200px;}
75% {top: 50px;}
100% {top: 100px;}
}
/* Standard syntax */
@keyframes myturn {
0% {top: 0px;}
25% {top: 200px;}
75% {top: 50px;}
100% {top: 100px;}
}