Categories
Web development

CSS animation-fill-mode Property

CSS animation-fill-mode Property

The CSS animation-fill-mode property defines a style for the element when the animation is not playing (before it starts, after it ends, or both).

Syntax:

animation-fill-mode: none|forwards|backwards|both;

none (default) – animation will not apply any styles to the element before or after it is executing.

forwards – the element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

backwards – the element will get the style values that is set by the first keyframe (depends on animation-direction), and retain this during the animation-delay period.

both – the animation will follow the rules for both forwards and backwards, extending the animation properties in both directions.

Example1:

<!DOCTYPE html>
<html>
<head>
<style>

.square-1, .square-2 {
  width: 100px;
  height: 100px;
  margin: 5px;
  background: #2a9d8f;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: move;
}
    
.square-1 {
  animation-duration: 4s;      
  animation-fill-mode: none;
}
.square-2 {
  animation-duration: 4s;  
  animation-fill-mode: forwards;
}

@keyframes move {
  from {left: 0px;}
  to {left: 250px;}
}
</style>
</head>
<body>

<div class="square-1">1</div>
<div class="square-2">2</div>

</body>
</html>

Output:

Square 1 (animation-fill-mode: none;) after the animation cycle will back to the beginning position. Square 2 (animation-fill-mode: forwards;) will retain the style values from the last keyframe when the animation ends.

1
2

Click on the square to repeat the animation.


Example2:

<!DOCTYPE html>
<html>
<head>
<style>

.square-1, .square-2 {
  width: 100px;
  height: 100px;
  margin: 5px;
  background: #2a9d8f;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: move;
  animation-delay: 1s;
}
    
.square-1 {
  animation-duration: 4s;      
  animation-fill-mode: backwards;
}
.square-2 {
  animation-duration: 4s;  
  animation-fill-mode: both;
}

@keyframes move {
  from {left: 0px;}
  to {left: 250px;}
}
</style>
</head>
<body>

<div class="square-1">1</div>
<div class="square-2">2</div>

</body>
</html>

Output:

1
2

Click on the square to repeat the animation.


Enjoy coding!

Read also:

CSS Transition

CSS animation-timing-function Property