Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a CSS3 animation from jumping back to the beginning when finished

I have a CSS3 animation, that simply moves a <div> down (via top: 0px; to top: 300px;). But my problem is, I don't know how to prevent the <div> from returning to the top when the animation is finished. Is there a way I can prevent this?

Here's a sample fiddle: http://jsfiddle.net/y8tJ7/

like image 586
BenjiWiebe Avatar asked Jan 15 '13 01:01

BenjiWiebe


People also ask

How do you make animation not go back in CSS?

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

Can you pause CSS animation?

CSS helps to animate HTML elements without using JavaScript. You can play and pause the animation applied to HTML elements using animation-play-state property of CSS.

How do you end an animation in CSS?

CSS animations emit events, so you can use the animationend event to intervene when the animation ends. const element = document. getElementById("element-to-be-animated"); element. addEventListener("animationend", () => { // Set your final state here.

How do I delay the start of a CSS animation?

The CSS animation-delay property has the following syntax: animation-delay: [time] | initial | inherit; As you can see, there are three possible values: time, initial, and inherit. The first option is [time], which is the number of seconds or milliseconds before the animation starts.


1 Answers

You need to invert the animation like so.

@keyframes move {
  from{
    top: 20px;
  }
}

See http://jsfiddle.net/gleezer/y8tJ7/1/

This way its finishing position is specified in the div styling and you only specify the beginning state in the keyframe.

EDIT: Another way of achieving it could be to simply add:

animation-fill-mode: forwards.

See this other fiddle.

Some more info about it on Mozilla Dev Network.

like image 102
Aurelio Avatar answered Nov 17 '22 21:11

Aurelio