Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu May 11, 2024 › #animation #Button

How to create an infinite shaking button with CSS animation

In this article, I will guide you how to create an infinite shaking button with CSS Animation.

CSS Code :

<style>
.shaking-button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  animation: shake 0.5s infinite;
}
</style>
Try it Yourself »

Explanation :

  1. background-color: #4CAF50;: Sets the background color of the button to a green shade.
  2. border: none;: Removes the default button border.
  3. color: white;: Sets the text color of the button to white.
  4. padding: 15px 32px;: Adds 15px padding to the top & bottom and 32px padding to the left & right.
  5. text-align: center;: Centers the text within the button.
  6. text-decoration: none;: Removes any default text decoration (example- underline).
  7. display: inline-block;: Displays the button as an inline-block element.
  8. font-size: 16px;: Sets the font size of the button text.
  9. margin: 4px 2px;: Adds some margin around the button.
  10. cursor: pointer;: Changes the cursor to a pointer when hovering over the button.
  11. animation: shake 0.5s infinite;: This is the key part that adds the shaking animation to the button. The animation property has three values:
    • shake: The name of the animation, which is defined in the @keyframes rule below.
    • 0.5s: The duration of the animation, which is 0.5 seconds.
    • infinite: The animation will repeat again and again.
    <style>
    @keyframes shake {
      0% { transform: translate(1px, 1px) rotate(0deg); }
      10% { transform: translate(-1px, -2px) rotate(-1deg); }
      20% { transform: translate(-3px, 0px) rotate(1deg); }
      30% { transform: translate(3px, 2px) rotate(0deg); }
      40% { transform: translate(1px, -1px) rotate(1deg); }
      50% { transform: translate(-1px, 2px) rotate(-1deg); }
      60% { transform: translate(-3px, 1px) rotate(0deg); }
      70% { transform: translate(3px, 1px) rotate(-1deg); }
      80% { transform: translate(-1px, -1px) rotate(1deg); }
      90% { transform: translate(1px, 2px) rotate(0deg); }
      100% { transform: translate(1px, -2px) rotate(-1deg); }
    }
    </style>
    Try it Yourself »

    The @keyframes rule defines the actual animation. It specifies the different positions and rotations the button should take at various points during the 0.5-second animation. The transform property is used to move and rotate the button.

save
listen
AI Answer
Write Your Answer
loading
back
View All