Positioning an animated gif over a jpg image

It is a tweet from Ryan Seddon that gave me the idea to use a <img> element with a background image to reduce the weight of large animated (gif) images.

The original image the artist is using is an animated gif file that weighs 387.5 kb

I sliced the image to save the animated part as a gif file (size 152.7 kb) and the static part as a jpg file (size 66.7 kb). The gif is the image in the markup, the jpg its background. The technique adds an extra http request, but I believe the 170 kb savings makes up for it 🙂

The markup

<img alt="" src="the-gif.gif">


img {
    padding: 472px 396px 60px 140px;
    background:url(https://css-101.org/wp-content/themes/pdp2el2eea4t8lgnlodsp145683/files/articles/two-layer-image/the-jpg.jpg) no-repeat;
Spinning dice

The image above is not the original one used for calculation of file weight.

Throwing a .png file into the picture

I didn’t spend much time on creating the animated gif which results in a choppy animation and some slight misalignment. Then, I had another idea: to hide part of the gif I am using a third image as an overlay – placing the gif between the jpg and a png.
As shown below:

Spinning dice Overlay

Note: I did not bother using a filter (for transparency in Internet Explorer).

The jpg

Background for the animated GIF

The gif

Animated GIF