简体   繁体   中英

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> 

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> 

Use animation-fill-mode property

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM