Is it possible to restart gif using CSS (without JS)?

So I have a piece of CSS:

.three-image-widget div.hover-icon img.original { display: block; } .three-image-widget div.hover-icon img.hovered { display: none; } .three-image-widget div.hover-icon:hover img.original { display: none; } .three-image-widget div.hover-icon:hover img.hovered { display: block; } 

I have .original images like .png , and .hovered images .hovered animated .gif that I want to run when they hover over div.hover-icon elements. I know that this can be done using JavaScript hack as follows:

 $('div.hover-icon').hover(function(){ $(this).find('.original').hide(); var hov = $(this).find('.hovered'), copy = hov.attr('src'); hov.attr('src','').attr('src',copy); }); 

but can I do the equivalent with pure CSS?

+5
source share
2 answers

No, you can’t. You need to reload the GIF, and CSS cannot do this.

+3
source

The closest thing I could figure out with pure CSS is to change the url to :hover , but it will only reset once:

 div { background-image: url(http://i.imgur.com/6wffOji.gif); height:50px; width: 100px; } div:hover { background-image: url(http://i.imgur.com/6wffOji.gif?v=1); } 
 <div></div> 

This approach will require you to use background-image instead of the <img> .


Edit:. Another method is to convert GIF images to 1 sprite column, where each frame is placed in a row under each other, and then uses CSS @keyframes and animation to better control image animation, you can change, rotate, control the duration, etc.

Simple GIF (animated):

basic gif animation

GIF script (no animation, static image):

gif animation sprite

code:

 div { height:50px; width: 100px; background-image: url(http://i.imgur.com/3YMNTbS.gif); } div:hover { animation: gif steps(6) 0.5s forwards; } @keyframes gif { to {background-position: 0 100%;} } 
 <div></div> 

As you can see, the state :hover triggers the keyframes of the gif animation. the steps(n) function is the key here, it will go through the frames in steps instead of a continuous transition. n is the number of frames in your sprite.

I used SpritePlane to create a sprite using Photoshop. It's easy to create a sprite and the size is about the same; you can save JPEG for more compression or PNG for a smooth alpha channel (you can also compress).

+2
source

Source: https://habr.com/ru/post/1247647/


All Articles