Positioning an animated gif over an image

This article was first published on css-101.org (04-19-2011).

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">

The CSS

img {
    padding: 472px 396px 60px 140px;
    background:url(the-jpg.jpg) no-repeat;
}

The Result

Spinning dice Spinning dice (this image 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 3 layers (Note that I did not bother using a filter for transparency in Internet Explorer.)

The jpg

Background for the animated GIF

The gif

Animated GIF

Share