DEV Community

Cover image for Play animation only on hover
b-meet
b-meet

Posted on

1

Play animation only on hover

Recently, I came across a situation where I had to animate a element only on hover. On browsing the internet for some amount of time, I found a very easy and reliable way to achieve this.

There is a built in CSS property to do this animation-play-state which tells the browser should the animation be running or paused.

I used it in combination with :hover to play animation only on hover.

Here is the code example

HTML

<div>
   <p className='figure'></p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.figure {
  width: 200px;
  height: 200px;
  background-color: aqua;
  animation: change 1s infinite;
  animation-play-state: paused;
}

@keyframes change {
  from {
    background-color: red;
  }

  to {
    background-color: pink;
  }
}

.figure:hover {
  animation-play-state: running;
}
Enter fullscreen mode Exit fullscreen mode

That's it you got to know how to animate on hover.

Stay happy, Keep your surroundings clean,
Signing off Meet Bhalodiya,

Peace ✌

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →