CSS animation-play-state Property Tutorial

In this section, we will learn what the animation-play-state property is and how to use it in CSS.

Click here to run the example of animation-play-state property.

CSS animation-play-state Property Definition and Usage

CSS provided a property named animation-play-state by which we can control whether to stop an animation that is playing or let it play.

Note: this property is mostly used within JavaScript codes.

CSS animation-play-state Property Syntax

animation-play-state: paused|running|initial|inherit;

CSS animation-play-state Property Value

The values set for this property are:

  • running: this is the default value and when
    used, the target animation will play.

  • paused: using this value we can stop an element
    from playing. It actually stops the animation right where it is and the
    next time we hit the animation to play, it will start its progress right
    where it was.

Note: the two global values “initial” and “inherit” values can also be used for this property.

Example: animation-play-state property in CSS

<!DOCTYPE html>
<html>
<head>
<title>CSS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
*{
margin:unset;
box-sizing: border-box;
}
div{
margin: 2em;
}
li{
animation-name:padding;
animation-delay: 2s;
animation-duration:10s;
animation-fill-mode: forwards;
display: inline-block;
border:thin solid lightgray;
border-radius: 1em;
margin-left: 0.2em;
padding:0.2em;
}
@keyframes padding{
from{
padding-bottom:0.2em;
}to{
padding-bottom:15em;
}
}
li:nth-child(1){
animation-timing-function: ease;
}
button{
margin:2em;
padding:2em;
border-radius: 0.2em;
border: thin solid lightblue;
}
</style>
</head>
<body>
<button class = "button">Stop Animation</button>
<ul>
<li class = "item">the linear animation</li>
</ul>
<script>
(function fun(){
let button = document.getElementsByClassName("button")[0];
let item = document.getElementsByClassName("item")[0];
let running = true;
button.addEventListener("click",(event)=>{
if (running){
item.style.animationPlayState = "paused";
button.innerText = "Start Animation";
running = false;
}else{
item.style.animationPlayState = "running";
button.innerText = "Stop Animation"
running = true;
}
});
})();
</script>
</body>
</html>

How Does CSS animation-play-state Property Work?

The animationPlayState method is the JavaScript version of the CSS animation-play-state property and as you can see we used this method in order to stop and start the animation when necessary.

Note: you can learn more about JavaScript in JavaScript tutorial section.