Open In App

How to shake an image using CSS Keyframe ?

In this article, we will see how to shake an image using CSS Keyframe, along with knowing the different properties used to shake the image, through the code example.

A shaking image or shivering effect on the image is used to make the website look more dynamic and attractive. This effect can be applied to images using @keyframes rules, which provides more control over the animation we want to perform on web pages. 



Approach: Shake effect on the images can be created using HTML and CSS, first we will insert an image using the <img> tag in HTML, then we will use the @keyframes rule to specify the animation code.

HTML code: Using HTML we will insert an image to our web page.



index.html:




<!DOCTYPE html>
<html>
  
<head>
    <title>Shake image in CSS</title>
    <link rel="stylesheet" 
          href="styles.css">
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <h3>
          How to shake an image using CSS Keyframe
      </h3>
    <img src=
         alt="GFG_img">
</body>
  
</html>

CSS code: In this section of code, first we will set the height and width of the image, then to apply the shivering effect we will use the @keyframes rule, first, we will create an animation named Shake under the hover effect, then we will use transform property to rotate the image in clockwise and anti-clockwise direction alternatively. If we will hover over the image, the image will seem to be shaking. The following are the CSS properties that are utilized with their brief description:

styles.css:




body {
    padding: 10px 20px;
    text-align: center;
    background-image: linear-gradient(to right, rgba(193, 245, 133, 0), 
                                                  rgba(91, 251, 77, 0.903));
}
  
img {
    height: 50%;
    width: 50%;
    margin: auto;
}
  
img:hover {
    animation: Shake 0.5s linear infinite;
}
  
/*Using keyframes for shaking an image*/
@keyframes Shake {
    0% {
        transform: rotate(5deg);
    }
  
    25% {
        transform: rotate(-6deg);
    }
  
    50% {
        transform: rotate(5deg);
    }
  
    75% {
        transform: rotate(-6deg);
    }
  
    100% {
        transform: rotate(5deg);
    }
}

Output:


Article Tags :