CSS code snippet to shake div element on mouse hover

By Faruque Ahamed Mollick

Here in this post I am going to give you a simple CSS code snippet which will shake a div element on mouse hover. In this code I am going to use CSS @keyframes rule which use for giving animation effect to any div element on a web page. CSS @keyframes rule was introduced in CSS3.

With @keyframes rule I have use CSS transform property. The transform property of CSS also introduced in the advance CSS3 and this property applies a 2D or 3D transformation to an element. CSS transform property allows you to rotate, scale, move, skew in a easy way.

Here is the CSS code snippet that I will use to shake a div element on mouse hover:

.shakethis {
  width: 150px;
  height: 150px;
  background: red;
}
.shakethis:hover {
  animation: shakeanimation;
  animation-duration: 1s;
  transform: translate3d(0, 0, 0);
}

@keyframes shakeanimation {
  15%, 85% {
    transform: translate3d(-2px, 0, 0);
  }
  
  25%, 75% {
    transform: translate3d(4px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-8px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(8px, 0, 0);
  }
}

I have make the duration for the animation one second. The animation-duration property define the duration of the animation. It tells for how much time the animation should play.

Also read:

Now you just need to put the below code inside the <body> tag of your HTML file where you would like it to be appear:



<div class="shakethis"></div>

That’s all you need. You can also modify it later if you wish. But here I have made the code as simple as I can do so that you can modify it easily.

Now test it on your chrome browser. You will see a red box on that HTML page. now hover your mouse cursor on it. What will you see?

You can see the red box is shaking nicely and then stop after one second as I have set the animation-duration property as 1 second. If you again hover on the element then the same thing will happen again.

Download shake on hover CSS code

If you want to download the complete HTML file then here is the link – shakeonhove.zip. After downloading the zip file there is only one HTML file inside it which contain the required code. Inside the <head> tag I have put the CSS code.

This is a simple HTML file with few line of code. After you download it, you can modify it, change color and anything. play with it as you like.

Leave a Reply

Your email address will not be published. Required fields are marked *