Niralana
Niralana

Reputation: 179

Smooth mouse-out animation

I have a diamond shaped div that spins 360 degrees around its own axis on hover by using CSS animation.

I can't work it out how to ensure smooth going back to the original state when not hovering anymore?

So far it "jumps" when the diamond is in the middle of its turn. I would like it to be smooth. Is it possible to do it with CSS animations? If not, maybe with JS?

.dn-diamond {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: #000;
  transform: rotate(-45deg);
  margin: 50px;
  overflow: hidden;
}
.dn-diamond:hover {
  animation: spin 3s infinite linear;
}
@keyframes spin {
  from { transform: rotateY(0deg) rotate(-45deg); }
  to   { transform: rotateY(360deg) rotate(-45deg); }
}
<div class="dn-diamond">

Here is JSFiddle

I was trying to use the transition but could not keep the original transformed shape of it (it went back to being a square, not a diamond).

Upvotes: 3

Views: 3754

Answers (2)

web-tiki
web-tiki

Reputation: 103770

You should use transitions for this. They will allow you to keep the transition smooth when the mouse moves out of the element.

Example :

.dn-diamond {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: #000;
  transform: rotateY(0deg) rotateZ(-45deg);
  transition: transform 3s linear;
  margin: 50px;
  overflow: hidden;
}
.dn-diamond:hover {
  transform: rotateY(360deg) rotateZ(-45deg);
}
<div class="dn-diamond">


You can also control the speed of the transition when the cursor moves out of the element by setting the transition property on normal and hover state.

Example :

.dn-diamond {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: #000;
  transform: rotateY(0deg) rotateZ(-45deg);
  transition: transform 0.5s linear;
  margin: 50px;
  overflow: hidden;
}
.dn-diamond:hover {
  transform: rotateY(360deg) rotateZ(-45deg);
  transition: transform 3s linear;
}
<div class="dn-diamond">

Note that in the above demos the vendor prefixes aren't included. check canIuse to know which vendor prefixes you need according to the browsers you want to support.

Upvotes: 5

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Give transitions for transform:

  -webkit-transition: -webkit-transform 3s ease-in;
     -moz-transition: -moz-transform 3s ease-in;
       -o-transition: -o-transform 3s ease-in;
          transition: transform 3s ease-in;

Snippet:

.dn-diamond {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: #000;
  transform: rotateY(0deg) rotateZ(-45deg);
  transition: transform 0.5s linear;
  margin: 50px;
  overflow: hidden;
}
.dn-diamond:hover {
  transform: rotateY(360deg) rotateZ(-45deg);
  -webkit-transition: -webkit-transform 3s ease-in;
  -moz-transition: -moz-transform 3s ease-in;
  -o-transition: -o-transform 3s ease-in;
  transition: transform 3s ease-in;
}
<div class="dn-diamond">

Upvotes: 3

Related Questions