To animate an element in CSS, you first create a named animation, then attach it to an element in that element’s property declaration block.
Keyframe rule
To create an animation, use the
@keyframes
rule followed by a name of your choosing, which will serve as the identifier for the animation.
The syntax involved may look kind of strange, but here’s the basic structure:
snippet
@keyframes animationName {
from {
/* list CSS properties here */
}
to {
/* list CSS properties here */
}
}
Keyframes can be specified in any order; it’s the percentage values, rather than the order of the declarations, that determine the sequence of keyframes in the animation.
Here are a few simple animations:
snippet
@-webkit-keyframes 'appear' {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@-webkit-keyframes 'disappear' {
to {
opacity: 0;
}
from {
opacity: 1;
}
}
@-webkit-keyframes 'appearDisappear' {
0%, 100% {
opacity: 0;
}
20%, 80% {
opacity: 1;
}
}
The last animation is worth paying extra attention to: we’ve applied the same styles to 0% and 100%, and to 20% and 80%. It means the element will start out invisible (opacity: 0;), fade in to visible by 20% of the way through the duration, remain visible until 80%, then fade out.