CSS animation-fill-mode
The animation-fill-mode property specifies how a CSS animation should apply styles to its target before and after it is executed.
There are four possible values for the animation-fill-mode property:
none: Default value. The animation will not apply any styles to the target before or after it is executed.forwards: The target will retain the computed values set in the last keyframe after the animation ends.backwards: The target will obtain the computed values set in the first keyframe during the period before the animation plays.both: The target will have the styles set in both the first and last keyframes applied during the animation.
Let's see some examples to understand how animation-fill-mode works:
.box {
width: 100px;
height: 100px;
background-color: red;
animation-name: slide;
animation-duration: 2s;
animation-fill-mode: forwards;
}
@keyframes slide {
from {
margin-left: 0;
}
to {
margin-left: 200px;
}
}
In this example, the animation-fill-mode property is set to forwards. This means that the red box will retain the margin-left value set in the last keyframe after the animation ends.
.square {
width: 100px;
height: 100px;
background-color: blue;
animation-name: spin;
animation-duration: 2s;
animation-fill-mode: backwards;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
In this example, the animation-fill-mode property is set to backwards. This means that the blue circle will obtain the transform value set in the first keyframe during the period before the animation plays.
Experiment with different values for the animation-fill-mode property to see how it affects the behavior of CSS animations in your projects.