Reputation: 697
When I create an @keyframes animation and assign it to an image on hover, it keeps flickering at random times. As you can see in the GIF, it only works properly a few random times.
I've already tried all of the following and prefix vendors for each:
backface-visibility: hidden;
animation-fill-mode: forwards;
transform-style: preserve-3d;
Why does this occur, and how can it be fixed?
This can be replicated in the this jsfiddle
Upvotes: 3
Views: 1570
Reputation: 9849
The problem is the image moves away from your mouse, which causes it to lose its animation.
Illustration (#
= the mouse cursor):
First, you focus it with your mouse animating it:
--------
| # |
--------
Next render, it loses the mouse focus and thus loses its animation:
-------
# | |
-------
Next render, it goes back to its original state because it no longer has the :hover
state:
--------
| # |
--------
And again, it will animate:
-------
# | |
-------
If you instead hover the parent element, it will keep focus on that parent element. You can then use parent:hover > child { animate }
:
----------------------
| ----- |
| | # | |
| ----- |
----------------------
----------------------
| ----- |
| # | | |
| ----- |
----------------------
One way to fix this is by setting the hover on the parent element:
.imgwrapper > img {
height: 100px;
background-color: red;
backface-visibility: hidden;
animation-fill-mode: forwards;
transform-style: preserve-3d;
display:inline-block;
}
.imgwrapper:hover > img {
animation: move 1s;
}
@keyframes move {
0% {
transform: translateX(100px);
}
100% {
transform: translate(0);
}
}
<div class="imgwrapper">
<img src="http://place-hold.it/300x500?text=New Text&bold"/>
</div>
Upvotes: 3
Reputation: 6827
As @Randy explained in the comment The second you move it, your mouse is no longer on the image. and that causes the bug. you can simply solve this by wrapping the image with a <div>
and use : hover
on the <div>
Here is a sample code for you:
div {
display: inline-block;
}
img {
height: 100px;
background-color: red;
backface-visibility: hidden;
animation-fill-mode: forwards;
transform-style: preserve-3d;
}
div:hover img {
animation: move 1s;
}
@keyframes move {
0% {
transform: translateX(100px);
}
100% {
transform: translate(0);
}
}
<div>
<img src="http://www.stickpng.com/assets/images/584181fda6515b1e0ad75a33.png" />
</div>
<p>
Sometimes a strange flicker occurs on hover.
</p>
Hope this was helpful for you.
Upvotes: 1
Reputation: 646
Use transition speed for the Image, so you can get smooth effects. Use this following code.
img{
-webkit-transition: .3s ease-out;
transition: .3s ease-out;
}
Upvotes: -2