Open In App
Related Articles

How to pause/play animation using CSS ?

Improve Article
Improve
Save Article
Save
Like Article
Like

CSS helps to animate HTML elements without using JavaScript. You can play and pause the animation applied to HTML elements using animation-play-state property of CSS.

The animation-play-state property has 2 values:

  • paused – Pauses an ongoing animation.
  • running – Starts a paused animation (default value).

Follow these steps :

  • Create HTML file
  • Create CSS file:
    1. Specify the position property for<div>tag.
    2. Use the animation property to mention the animation you want to give to the <div>tag.
    3. Use the animation-play-state property to play/pause the animation.
    4. Mention the keyframes propertiesfrom’ and ‘to’ to mention the start and end of the animation.

Example 1: HTML and CSS code to play the animation.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        div {
            position: relative;
            animation: geeks 5s infinite;
            animation-play-state: paused;
        }
          
        div:hover {
            animation-play-state: running;
        }
          
        @keyframes geeks {
            from {
                left: 0px;
            }
            to {
                left: 100px;
            }
        }
    </style>
</head>
  
<body>
    <p>
        Hover over the GeeksforGeeks 
        to run the animation.
    </p>
  
    <div>GeeksforGeeks</div>
</body>
  
</html>


Output:

Play animation when hovered

Example 2: HTML and CSS code to pause the animation.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        div {
            position: relative;
            animation: geeks 5s infinite;
        }
          
        div:hover {
            animation-play-state: paused;
        }
          
        @keyframes geeks {
            from {
                left: 0px;
            }
            to {
                left: 100px;
            }
        }
    </style>
</head>
  
<body>
    <p>
        Hover over the GeeksforGeeks 
        to stop the animation.
    </p>
  
    <div>GeeksforGeeks</div>
</body>
  
</html>


Output:

Pause animation when hovered


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 06 Apr, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials