super-user
super-user

Reputation: 1057

CSS 3 Stop Rotate Animation After N seconds after page load

I don't have much knowledge in css3 and I got this code fragment that makes a div spin infinitely.

.spin {
  -webkit-animation: rotation 0.4s linear infinite;
  animation: rotation 0.4s linear infinite;
  -webkit-transform: translateX(100%) translateY(-100%) rotate(45deg);
  transform: translateX(100%) translateY(-100%) rotate(45deg);
}

@-webkit-keyframes rotation {
    0%      { -webkit-transform: rotate(0deg); }
    50%     { -webkit-transform: rotate(-180deg); }
    100%    { -webkit-transform: rotate(-360deg); }
}

@keyframes rotation {
    0%      { transform: rotate(0deg); }
    50%     { transform: rotate(-180deg); }
    100%    { transform: rotate(-360deg); }
}

I want to stop the rotation after a couple of seconds but I don't know what to change. I tried changing infinite to 3 but it stopped and placed my div somewhere else. I need a smooth stop and retains the div original position.

Upvotes: 0

Views: 8108

Answers (1)

Mihai T
Mihai T

Reputation: 17697

see here jsfiddle

the element was moving because of the translate

code :

.spin {
 height:50px;
 width:50px;
 background:red;
 -webkit-animation: rotation 0.4s linear 3;
 animation: rotation 0.4s linear 3;
 -webkit-transform: rotate(45deg);
 transform:  rotate(45deg);
}

you should know that the infinite is a value of the animation-iteration-count property which specifies the number of times an animation should be played. so not the seconds.

if you want to stop after N seconds use animation-duration and i suggest you divide the animation declaration into parts, like this :

jsfiddle

for ex you want the spin to rotate for 2 seconds, if you set animation-duration to 2 seconds, the whole animation will take 2 seconds to complete, and that's not what you want. You want your spin to rotate fast for 2 seconds, so you need to calculate the animation-iteration-count like this 2second/animation-duration

say you want 1 rotation to be completed in 0.5s, you set the animation-duration:0.5s and then animation-iteration-count to 2s/0.5 = 4

code :

spin {
  height:50px;
  width:50px;
  background:red;

  -webkit-transform: rotate(45deg);
  transform:  rotate(45deg);
  animation-name:rotation;
  animation-delay:0s;
  animation-duration:0.5s;
  animation-iteration-count:4;
  animation-fill-mode:backwards;
}

for more info about animations, read here : CSS3 animation Property

Upvotes: 4

Related Questions