Wednesday, 8 February 2012

CSS: image preloader


Today we are going to explore another CSS basic usage: image preloaders. It is a good practise not to use big images (in terms of weight) for web sites, however sometimes it's part of the game. Just consider the fact that a web site may be centred on photography and high resolution pictures may constitute its most important element.
In those cases, images may take a while to load and empty boxes shown on the home page aren't really a good welcoming sight for users.
With CSS we can reproduce a loading gif like:
which will be displayed while the main image is being loaded.
Let's see how we can do it.

We need to create a container for the image:

<div class="preloader">
   <img src="image.path.jpg" width="840" height="281">
The image sits inside a div with class="preloader". In the img tag we set the original width and height of the image (840 and 281 are just examples).

With some basic rules, we can style the image container:
    width: 852px;
    height: 293px;
    padding: 5px 5px 5px 5px;
    border: solid 1px #000000;
The width and the height of the container is considering the image size and the borders and padding (840+5+5+2=852 and 281+5+5+2=293). The above rules can be changed according to your needs, as usual.
Now we set rules for the image itself:
div.preloader img
    display: block;
    background-image: url(images/loading.gif);
    background-repeat: no-repeat;
    background-position: center center;
We use as background image the animated gif shown above (the classic rotating gif, but you can use the one you prefer as long as it is showing that something is going on). We position it at the centre of the container, without repeat.
And that is all. While the big image is loading, the user will see the animated gif. When the big image has been loaded, it will cover and hide the animated gif.

Hope you liked the example and see you next time.


  1. I was expecting more of a jQuery solution for this!

    One that loads the image when it's scrolled to on screen would be great.
    This would help save bandwidth if the user doesn't scroll down the page to view images that aren't on screen upon page load.

    Keep up the good work :)

    1. Ben, you're right, but - as the title states - this is a CSS solution :-) And let me say, very, very basic and simple. A jQuery solution is possible - and there are many. I will write a post about it.
      Thanks for pointing that out!


Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.