How To Stop Css Animation On Hover

In this blog post, we will explore how to stop CSS animations on hover. This can be useful in various web design situations, especially when you want to draw attention to specific elements only when users hover over them. Let’s get started!

1. Create a simple CSS animation

First, let’s create a simple CSS animation. We’ll create a box that moves from left to right using the @keyframes rule and the animation property. Here’s an example:

  .box {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    animation: move 5s linear infinite;
  }

  @keyframes move {
    0% { left: 0; }
    100% { left: 100%; }
  }
  

This will create a red box that moves from left to right in a loop. Now, let’s learn how to stop this animation on hover.

2. Pause the animation on hover

To stop the CSS animation on hover, we can use the :hover pseudo-class and change the animation-play-state property to paused. Here’s the code:

  .box:hover {
    animation-play-state: paused;
  }
  

By adding this rule, when the user hovers over the box, the animation will pause, and when the user moves the cursor away, the animation will resume.

3. Example

Here’s a complete example to demonstrate how to stop a CSS animation on hover:

  
  
  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stop CSS Animation on Hover Example</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        animation: move 5s linear infinite;
      }

      @keyframes move {
        0% { left: 0; }
        100% { left: 100%; }
      }

      .box:hover {
        animation-play-state: paused;
      }
    </style>
  
  
    <div class="box"></div>
  
  
  

Copy and paste the above code into your HTML file, and you’ll see a red box moving from left to right. When you hover over the box, the animation will pause, and when you move your cursor away, the animation will resume.

Conclusion

Stopping a CSS animation on hover is a simple yet effective way to pull a user’s focus on specific elements. By changing the animation-play-state property to paused when the user hovers over the element, you can create interactive and engaging designs. Give it a try and see how it can enhance your web projects!