I have an animation when the page load and when you hover over the element. my issue is when the hover animation finishes the first one replays. is there any way to stop/prevent it from replaying?
img {
height: 40px;
width: auto;
position: absolute;
animation-name: test1;
animation-duration: 4s;
}
img:hover {
animation-name: test2;
animation-duration: 4s;
}
@keyframes test1 {
from {height: 40px}
to {height: 80px}
}
@keyframes test2 {
from {height: 40px}
to {height: 80px}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<img src="https://media.discordapp.net/attachments/874191575004094524/946077618992738375/grey.png" alt="">
</body>
</html>
>Solution :
The test1 animation restarts because your :hover rule removes the test1 animation from img‘s animation-list (and adds test2), and then when the :hover state is left the test1 animation is re-added, which makes it restart the test1 animation again.
The fix is to not remove the test1 animation from the :hover state, like so:
img {
height: 40px;
width: auto;
position: absolute;
animation-name: test1;
animation-duration: 4s;
}
img:hover {
animation-name: test1, test2;
animation-duration: 4s, 4s;
}
Demo:
img {
height: 40px;
width: auto;
position: absolute;
animation-name: test1;
animation-duration: 4s;
}
img:hover {
animation-name: test1, test2;
animation-duration: 4s, 4s;
}
@keyframes test1 {
from { height: 40px; }
to { height: 80px; }
}
@keyframes test2 {
from { height: 40px; }
to { height: 80px; }
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<img src="https://media.discordapp.net/attachments/874191575004094524/946077618992738375/grey.png" alt="">
</body>
</html>