How to prevent a CSS animation from going back to its original position?
Asked Answered
R

3

14

So, my CSS moves a div to -40px after 3 seconds. After doing so, the div is then moved back to its original position. Here is the code:

#jsAlert {
    width: 100%;
    height: 40px;
    position: absolute;
    left: 0px;
    top: 0px;
    background-color: rgba(0, 0, 0, 0.6);
    animation:mymove 3s;
    animation-delay: 3s;

    /*Safari and Chrome*/
    -webkit-animation: mymove 2s;
    -webkit-animation-delay: 2s;
}

@keyframes mymove {
    from {top: 0px;}
    to {top: -40px;}
}

@-webkit-keyframes mymove /*Safari and Chrome*/
{
    from {top: 0px;}
    to {top: -40px;}
}

How would I prevent the div from returning to its original position?

Rabbin answered 23/3, 2014 at 17:52 Comment(0)
I
33

You need to use animation-fill-mode with a value set to forwards

From Mozilla Developer Network:

The target will retain the computed values set by the last keyframe encountered during execution. The last keyframe encountered depends on the value of animation-direction and animation-iteration-count

Demo

Intuitional answered 23/3, 2014 at 17:55 Comment(0)
F
1

i would not recommend using @keyframes for this simple animation.

this article may help you

http://www.kirupa.com/html5/css3_animations_vs_transitions.htm

Conclusion There you have it - a candid look at what makes transitions and animations similar yet so very different. My general approach for determining when to use which goes like this:

If what I want requires the flexibility provided by having multiple keyframes and easy looping, then I go with an animation. If I am looking for a simple from/to animation, I go with a transition. If I want to manipulate the property values that I wish to animate using JavaScript, I go with a transition.

cause performance is a valuable thing .

Flat answered 23/3, 2014 at 18:3 Comment(0)
M
0

For anyone who gets here and is using an <animate> tag: fill="freeze" is the solution.

Midwifery answered 11/5, 2022 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.