CSS
🎯 CSS animation-fill-mode Property
The animation-fill-mode property dictates how an HTML element should behave **before the animation starts (during the delay period) and after the animation finishes**.
In short, this property allows you to control whether the element should snap back to its original state once the animation ends or stay fixed at the final keyframe's style.
🔧 animation-fill-mode Values and Their Meanings
This CSS property accepts 4 core values along with global CSS values. Each has a different impact on the animation cycle:
1️⃣ none
This is the default behavior. The element retains its original styles before the animation begins. As soon as the animation ends, it abruptly snaps **back to its original initial state**.
.box {
animation-fill-mode: none;
}
2️⃣ forwards
Once the animation completes, it forces the element to **retain the styles defined in the very last keyframe (`100%` or `to`)**. The element stays frozen right where the animation ends.
.box {
animation-fill-mode: forwards;
}
3️⃣ backwards
During the waiting period before the animation starts (during `animation-delay`), it **applies the styles from the first keyframe (`0%` or `from`)** to the element. Once the animation ends, the element returns to its original styles.
.box {
animation-fill-mode: backwards;
}
4️⃣ both
Combines the behaviors of both forwards and backwards. It applies the first keyframe's style during the delay period and retains the final keyframe's style after the animation ends.
.box {
animation-fill-mode: both;
}
5️⃣ initial
Resets the property to its default CSS value. In practice, it behaves exactly like none.
.box {
animation-fill-mode: initial;
}
🧪 Practical Example
If you want a button to gently fade in when the page loads and stay fully visible afterward, you must use forwards:
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.button {
animation-name: fadeIn;
animation-duration: 1.5s;
animation-delay: 1s;
animation-fill-mode: forwards;
}
Without forwards, the button would fade in, but the moment the animation ends, it would instantly snap back to being completely invisible (`opacity: 0`).
🚀 Why Is It Important?
Managing the states of an element before and after playback provides several core benefits:
- Prevents elements from abruptly flashing back to their original styles
- Ensures smooth visual transitions during animation delays
- Reduces the need for writing extra JavaScript to freeze elements
- Creates a much more polished and professional user experience (UX)
-
🧠 Quick Summary
- none: Displays original style during delay, snaps back to original style at the end.
- forwards: Keeps the final frame (`100%`) style after the animation ends.
- backwards: Applies the first frame (`0%`) style ahead of time during the delay period.
- both: Applies the first frame style before starting, keeps the final frame style after ending.
