Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Extend the animation properties in both directions with CSS
The CSS animation-fill-mode property with the value both extends animation properties in both directions − applying styles from the first keyframe before the animation starts and retaining styles from the last keyframe after the animation completes.
Syntax
selector {
animation-fill-mode: both;
}
How it Works
When animation-fill-mode: both is applied −
- Before animation: The element adopts styles from the first keyframe (0% or from)
- After animation: The element retains styles from the last keyframe (100% or to)
Example
The following example demonstrates extending animation properties in both directions ?
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 100px;
background: red;
position: relative;
animation-name: myanim;
animation-duration: 3s;
animation-delay: 1s;
animation-fill-mode: both;
}
@keyframes myanim {
from {
left: 0px;
background-color: green;
opacity: 0.5;
}
to {
left: 200px;
background-color: blue;
opacity: 1;
}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
A green box with 50% opacity appears at position 0px (first keyframe styles applied immediately). After a 1-second delay, it animates to the right while changing to blue with full opacity. After animation completes, it remains blue at the final position instead of reverting to the original red color.
Comparison with Other Fill Modes
| Value | Before Animation | After Animation |
|---|---|---|
none |
Original styles | Original styles |
forwards |
Original styles | Final keyframe styles |
backwards |
First keyframe styles | Original styles |
both |
First keyframe styles | Final keyframe styles |
Conclusion
Using animation-fill-mode: both creates seamless animations by applying keyframe styles both before and after the animation sequence. This is particularly useful when you want the element to maintain its animated state permanently.
Advertisements
