Reputation: 23
Why does the animation only work when element appear but not when you hover?
body {
text-align: center;
padding-top: 50px;
font-family: sans-serif;
}
span {
background: dodgerblue;
border-radius: 4px;
padding: 10px 20px;
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 4;
animation-delay: 3s;
}
span:hover {
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 1;
animation-delay: .2s;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0px dodgerblue
}
50% {
box-shadow: 0 0 0 20px transparent
}
100% {
box-shadow: 0 0 0 0px transparent
}
}
<span>
Test
</span>
https://codepen.io/umasterov/pen/XWJGLQV
if you remove the animation when it appears, the hover animation works
Upvotes: 2
Views: 60
Reputation: 18378
You have several options:
Duplicating the animation
body {
text-align: center;
padding-top: 50px;
font-family: sans-serif;
}
span {
background: dodgerblue;
border-radius: 4px;
padding: 10px 20px;
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 4;
animation-delay: 3s;
}
span:hover {
animation-name: pulse2;
animation-duration: 2s;
animation-iteration-count: 1;
animation-delay: .2s;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0px dodgerblue
}
50% {
box-shadow: 0 0 0 20px transparent
}
100% {
box-shadow: 0 0 0 0px transparent
}
}
@keyframes pulse2 {
0% {
box-shadow: 0 0 0 0px dodgerblue
}
50% {
box-shadow: 0 0 0 20px transparent
}
100% {
box-shadow: 0 0 0 0px transparent
}
}
<span>
Test
</span>
Using pseudo-element
body {
text-align: center;
padding-top: 50px;
font-family: sans-serif;
}
span {
position: relative;
display: inline-block;
background: dodgerblue;
border-radius: 4px;
padding: 10px 20px;
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 4;
animation-delay: 3s;
}
span:hover::before {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
border-radius: 4px;
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 1;
animation-delay: .2s;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 dodgerblue
}
50% {
box-shadow: 0 0 0 20px transparent
}
100% {
box-shadow: 0 0 0 0 transparent
}
}
<span>
Test
</span>
Upvotes: 1
Reputation: 26
You just need to take your animation off the normal state
body {
text-align: center;
padding-top: 50px;
font-family: sans-serif;
}
span {
background: dodgerblue;
border-radius: 4px;
padding: 10px 20px;
}
span:hover {
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: 1;
animation-delay: .2s;
}
@keyframes pulse {
0% {box-shadow: 0 0 0 0px dodgerblue}
50% {box-shadow: 0 0 0 20px transparent}
100% {box-shadow: 0 0 0 0px transparent}
}
Upvotes: 0