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.

This post was written by Marketing Enthusiast Jayme Blackmon, whose new book, Social SEO for Small Business, chronicles the methods of social media to gain search engine visibility. Learn more about this book.

Buy me a coffee

8 Comments

Elizabeth

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

Sam

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

Mark Davis

Great tip, thanks.

Briongloid

Yeah the “no-repeat” is the key.

Nicholas

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

link

Nicholas

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

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.

Oscar

completely flawless!

thanks a bunch,
oscar

ps. used for navbar/menu on http://www.040event.com