SirMaxime
SirMaxime

Reputation: 154

Maintain last color change in CSS Keyframe

So I made a CSS animation with keyframe where the background color of the element and the font color changes. The problem is, when it comes to the last frame, the colors get reset to the default ones. I used the animation-fill-mode and it helps to maintain the end size but the colors still reset? This is the code:

@keyframes anim{
  0% {background-color: #404880; color: #DCE0F7;}
  90% {background-color: #747AA6; color: #242D5E;}
  100% {font-size: 19px;}
}
.apply{
  font-size: 15px;
  background-color: #404880;
  border-radius: 5px;
  border-style: none;
  color: #DCE0F7;
}
.apply:hover{
  animation: anim;
  animation-duration: .5s;
  -webkit-animation-fill-mode:forwards; /*Chrome 16+, Safari 4+*/
  -moz-animation-fill-mode:forwards; /*FF 5+*/
  -o-animation-fill-mode:forwards; /*Not implemented yet*/
  -ms-animation-fill-mode:forwards; /*IE 10+*/
  animation-fill-mode:forwards; /*when the spec is finished*/
}

Upvotes: 4

Views: 4231

Answers (1)

Harry
Harry

Reputation: 89750

When you set animation-fill-mode: forwards, the state as at the last keyframe would be retained for the element even after the animation is complete. Here, you've not set value for either background-color or color in last keyframe (which is, the 100% frame) and so it goes back to the original value that was provided for the element (the default or un-hovered state). If you want it to retain the state as at 90% frame then the properties and its values should be carried over to the 100% frame also (even though there is no change).

For exactly the same reason that is mentioned above, you don't require the 0% frame in your settings because it has the same value as the default state of the element. The 0% frame is generally required only when the state at the start of the animation needs to be different from the default state.

@keyframes anim {
  90% {
    background-color: #747AA6;
    color: #242D5E;
  }
  100% {
    font-size: 19px;
    background-color: #747AA6;
    color: #242D5E;    
  }
}
.apply {
  font-size: 15px;
  background-color: #404880;
  border-radius: 5px;
  border-style: none;
  color: #DCE0F7;
}
.apply:hover {
  animation: anim;
  animation-duration: .5s;
  animation-fill-mode: forwards;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='apply'>Test content</div>

Upvotes: 7

Related Questions