Tom Maxwell
Tom Maxwell

Reputation: 9573

How to pause a CSS keyframe animation when it ends the first cycle?

I'm working on my first CSS keyframe animation and would like to know how it would be possible to pause an animation after it finishes its first run-through. You can check out my site here: http://www.tommaxwell.me and the grey quote at the bottom has a hover animation that you can see. However, once the animation is over it resets. How should I go about stopping it so that it stays in the end state of the animation when it's finished?

I know the use of a keyframe animation in this case is kind of lame and unnecessary, but I'm really just testing out keyframes, and will use it better later. :)

Upvotes: 2

Views: 6640

Answers (2)

Christofer Vilander
Christofer Vilander

Reputation: 18022

As @Mr. Alien answered, transitions is to prefer for this, but since you asked - it is possible to maintain the last state in an animation.

You do this by adding animation-fill-mode: forwards;

Here's a demo

Here's the code from my example:

HTML

<div class="text">Hover here</div>​

CSS

.text {
  color: blue;  
}

.text:hover {
    -webkit-animation: color 1.0s ease-in forwards;
       -moz-animation: color 1.0s ease-in forwards;
         -o-animation: color 1.0s ease-in forwards;
            animation: color 1.0s ease-in forwards;    
}

@-webkit-keyframes color {
  0%   { color: blue; } 
  100% { color: red;  }
}

@-moz-keyframes color {
  0%   { color: blue; } 
  100% { color: red;  }
}

@-o-keyframes color {
  0%   { color: blue; } 
  100% { color: red;  }
}

@keyframes color {
  0%   { color: blue; } 
  100% { color: red;  }
}

Here's a good resource if you want to read about the the ‘animation-fill-mode’ property. http://dev.w3.org/csswg/css3-animations/#animation-fill-mode-property

Upvotes: 7

Mr. Alien
Mr. Alien

Reputation: 157334

I know what you are doing here, use CSS transition instead

Demo

.class {
   color: #ff0000;
   transition: color 2s;
   -moz-transition: color 2s; /* Firefox 4 */
   -webkit-transition: color 2s; /* Safari and Chrome */
   -o-transition: color 2s; /* Opera */
}

.class:hover {
   color: #00ff00;
}

You wont be able to preserve the hovered state of your text, for that you need to use JavaScript

Upvotes: 2

Related Questions