In this section, we will learn what the animation-fill-mode property is and how to use it in CSS.
Click here to run the example of animation-fill-mode property.
CSS animation-fill-mode Property Definition and Usage
The thing about CSS animation is that it can’t affect the target element before the animation begins (during the animation delay time) and after it finished. Basically, after the animation is finished, the style of the element will return to what it was before the applied animation.
But CSS provided a property named `animation-fill-mode` that allows us to override this behavior.
Using this property, we can apply the style set in the first key-frame or last key-frame of the animation to the element, before and after the animation played.
CSS animation-fill-mode Property Syntax
animation-fill-mode: none|forwards|backwards|both|initial|inherit;
CSS animation-fill-mode Property Value
Here’s the list of values we can set for this property:
- none: This is the default behavior and it means no style of the animation should be applied to the target element before or after the animation played.
- backwards: it means while the element is in animation-delay time, apply the style that is set in the first key-frame of the animation to the target element. (depending on animation direction and animation-iteration-count, the first key-frame might end up being actually the last key-frame)
- forwards: it means after an animation is finished, apply the style that is set in the last key-frame of the animation to the target element. (depending on animation direction and animation-iteration-count, the last key-frame might end up being actually the first key-frame)
- both: it means while the element is in animation-delay time, apply the style that is set in the first key-frame of the animation to the target element and after the animation finished, apply the style that is set in the last key-frame of the animation, to the target element.
Example: animation-fill-mode property in CSS
See the Pen animation-fill-mode property in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.
How Does CSS animation-fill-mode Property Work?
In the example above, because the value of the animation-fill-mode is set to “backwards”, while the element is in animation-delay time, its background color becomes light-coral which is the style set for the first key-frame of the animation.
Example: CSS animation-fill-mode “forwards” value
See the Pen CSS animation-fill-mode “forwards” value by Enjoy Tutorials (@enjoytutorials) on CodePen.
In the example above, because the value of the `animation-fill-mode` is set to “forwards”, after the animation finished its execution, the background-color of the element becomes light-sky-blue which is the style set for the last key-frame of the animation.