Search code examples
htmlcsscss-animationskeyframe

How to start an keyframe animation automatically


I am making my first experiences with html css today. I have created an animation here that is triggered on hover. Now I want the animation to be triggered by itself after about 5 seconds without hover. How do I have to proceed here to achieve this?

Thanks for your help!

<html lang="en">
  <head>
    <title>Shake</title>
    <style>

    .shake:hover {
      animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
      transform: translate3d(0, 0, 0);
      backface-visibility: hidden;
      perspective: 1000px;
    }

    @keyframes shake {
      10%, 90% {
        transform: translate3d(-2px, 0, 0);
      }
  
      20%, 80% {
        transform: translate3d(4px, 0, 0);
      }

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

      40%, 60% {
        transform: translate3d(7px, 0, 0);
      }
    }
    </style>
  </head>
  <body>
    <div class="shake">Shake</div>
  </body>
</html>

Solution

  • You can remove the :hover pseudo class from the css and add animation-delay property for 5s (or whatever delay you want).

     .shake {
          animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
          transform: translate3d(0, 0, 0);
          backface-visibility: hidden;
          perspective: 1000px;
          animation-delay: 5s
        }
    
        @keyframes shake {
          10%, 90% {
            transform: translate3d(-2px, 0, 0);
          }
      
          20%, 80% {
            transform: translate3d(4px, 0, 0);
          }
    
          30%, 50%, 70% {
            transform: translate3d(-8px, 0, 0);
          }
    
          40%, 60% {
            transform: translate3d(7px, 0, 0);
          }
        }
    <html lang="en">
      <head>
        <title>Shake</title>
      </head>
      <body>
        <div class="shake">Shake</div>
      </body>
    </html>