11

I have a button that I want to rotate when the mouse hovers over it. However, while the spinning works when the mouse enters, it also spins when the mouse leaves. Here is what I mean:

button {
  transition: transform 1.2s linear;
}

button:hover {
  transform: rotate(360deg);
}
<button>X</button>

Is there any way to just make the mouse spin when the mouse enters?

4 Answers 4

32

Use animation instead of transition and make use of animation-play-stateMDN

button{
  animation: rotate360 1.2s linear infinite;  /* animation set */
  animation-play-state: paused;               /* ...but paused */
}
button:hover{
  animation-play-state: running;              /* Run on hover! */
}
@keyframes rotate360 {
  to { transform: rotate(360deg); }           
}
<button>X</button>

1
3

Try this snippet

button:hover {
  transition: transform 1.2s linear;
  transform: rotate(360deg);
}
<button>
X
</button>

3
  • That works! I was so close. Is there any way to make the button stay in the position it was when the user's mouse leaves?
    – MarksCode
    Commented Aug 11, 2016 at 6:16
  • @MarksCode Not possible with CSS I guess. Are you familiar with jQuery? Commented Aug 11, 2016 at 6:22
  • I am! I was looking for that
    – MarksCode
    Commented Aug 11, 2016 at 6:23
3

In previous examples when mouse leaves an element the transition resets to first state very suddenly. It's better to make the transition play back.

In this example button is animated when mouse is hovering and when mouse left it:

button {
   transition: transform 1.2s linear;
}
button:hover {
   transform: rotate(360deg);
}
<button>
X
</button>

0

try this

button:hover {
  transform: rotate(360deg);
  transition: transform 1.2s linear;
}
<button>
X
</button>

Not the answer you're looking for? Browse other questions tagged or ask your own question.