0

So I am learning about CSS animations for the first time, and I've stumbled across a problem.

Let's say I have a simple div with a width change animation on hover.

The problem is that the div goes back to 350px even if you're still hovering it. Is there a way to prevent that, so that the div stays to 400px until you are not hovering it?

Here is the code:

div {
  height: 90px;
  width: 350px;
  background-color: black;
}

div:hover {
  animation-name: hoverAnimation;
  animation-duration: 0.5s;
}

div:not(:hover) {
  animation-name: stopAnimation;
  animation-duration: 0.5s;
}

@keyframes hoverAnimation {
  from {width: 350px}
  to {width: 400px}
}

@keyframes stopAnimation {
  from {width: 400px}
  to {width: 350px}
}
<div></div>

And here is the code without the div:not(:hover) animation, which doesn't work either.

div {
  height: 90px;
  width: 350px;
  background-color: black;
}

div:hover {
  animation-name: hoverAnimation;
  animation-duration: 0.5s;
}

@keyframes hoverAnimation {
  from {width: 350px}
  to {width: 400px}
}
<div></div>

Sorry if this is a little confusing. All this is still fairly new to me. Thanks in advance!

Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17

1 Answers1

2

I've slightly changed your code to instead use a transition for the width change of the div when hovered.

div {
  height: 90px;
  width: 350px;
  background-color: black;
  transition: width .5s;
}

div:hover {
  width: 400px;
}
<div></div>
Sarah
  • 354
  • 1
  • 12