Preloading CSS Hover Images

If you are creating CSS hover states on an element using the background:url(images/background.jpg); method, you can preload your hover state images without using any javascript whatsoever. If you do a lot of css work, you can tell that when you load a page with this method, the background image on the hover takes a second to load when you hover over it. This can be eliminated very easily. Here’s an example using a div that has a class of button:

<div class=”button”>
<a href=”">my button</a>
</div>

In the css you will need to define with anchor tag definitions as well as the definition for the div element itself:

.button {
width:100px;
height:20px;
padding:5px;
margin:0px;
background:url(images/background-hover.jpg) no-repeat top left;
}

.button a:link, .button a:visited {
display:block;
width:100px;
height:20px;
padding:5px;
margin:0px;
background:url(images/background.jpg) no-repeat top left;
}

.button a:hover, .button a:active {
display:block;
width:100px;
height:20px;
padding:5px;
margin:0px;
background:url(images/background-hover.jpg) no-repeat top left;
}

The key is the highlighted line of code in the div. If you specify the hover state on the div element background, the image will be hidden by the a:link class background image, but it will be loaded when the page is loaded.

7 Comments

Elizabeth said...

What if I have a multiple of images with a multiple of different backgrounds?

Sam said...

Then you would create a different class or id for those individual buttons.

Mark Davis said...

Great tip, thanks.

Briongloid said...

Yeah the “no-repeat” is the key.

Nicholas said...

Even better, if the anchor has no background itself, you can use positioning to do it with just one element:

link

Nicholas said...

Sorry, I assumed that my html would be escaped!

That should have been <a style=”background: url(hover.png) -10000px -10000px no-repeat;”>

Adaptiv Media said...

This is another smart trick. There are three sort of main ways of achieving this in my mind and that’s;

Loading background images beneath the image that it rolls under (here)
Loading them at the end of a page’s code for wholesale loading.
Using one image containing each state and adjusting the position within the element t expose one area of the image.

Thanks.