driconmax driconmax -4 years ago 113
CSS Question

CSS Animation not working properly

I have a very simple animation that fades out and shrinks a

div
.

But the problem is that when the animation finishes it goes back to the start and stays there.



div {
background-color: red;
height: 80px;
}

.fade-out {
animation-name: fade-out;
animation-duration: 2s;
}

@keyframes fade-out {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 0; height: 0;}
}


<div class="fade-out">Style Test</div>




Answer Source

If you add animation-fill-mode: forwards; to your .fade-out rule it will fix your animation.

animation-fill-mode specifies how CSS rules should be applied before and after executing the animation. The default is none which means that before and after the animation is executed, it will not apply any of the animation styles. That's why you're seeing it revert to the pre-animation state.

forwards tells the browser to retain the styles from the last keyframe. That's what you're looking for.

See the MDN docs for more information.

div {
  background-color: red;
  height: 80px;
}

.fade-out {
    animation-name: fade-out;
    animation-duration: 2s;
    animation-fill-mode: forwards;
}

@keyframes fade-out {
    0% { opacity: 1; }
    50% { opacity: 0; }
    100% { opacity: 0; height: 0;}
}
<div class="fade-out">Style Test</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download