Preloading images for links in CSS
There is a pretty common problem when using semantic html and css for your navigation: having a little pause while the a:hover image is loading. Sure, it only happens once, but what if you’ve got several images for several different links? Let’s take the main navigation bar of my work site, grahamgilbert.com as an example.
Firstly, the markup I used. Ideally you should be using unordered lists for all your navigation since it helps screen reading software and the like.
<div id="header">
<ul>
<li><a href="index.html" class="homecurrent">home</a></li>
<li><a href="resume.html" class="resume">resume</a></li>
<li><a href="portfolio.html" class="portfolio">portfolio</a></li>
<li><a href="personal.html" class="personal">personal</a></li>
<li><a href="contact.php" class="contact">contact</a></li>
</ul>
</div>
All pretty standard so far. Each link has two classes (in this example, .home and .homecurrent for when it’s the active page. This isn’t required, but I used different images in the links to show the user which page they were on).
Now, you’d normally put something like this in your css:
#header a {
display: block;
height:300px;
width:120px;
}
#header a.homecurrent {
background-image: url(images/css/common/home-current.png);
}
#header a:hover.homecurrent {
background-image: url(images/css/common/home-current-hover.png);
}
This will of course work perfectly well, but you will have the pause while the hover image loads, which is what we want to avoid.
To get around this, fire up your image editor and put the images side by side like this:
In this example, each part of the image is 120px wide, so we will only show the first 120px of the background by specifying the width, and we will then change the position of the same background image for the hover. Since it’s the same image, we don’t need to specify another background.
#header a.homecurrent {
background-image: url(images/css/common/home-current.png);
}
#header a:hover.homecurrent {
background-position:-120px 0;
}
I’ll just quickly explain the background-position property since you may not have seen it before. The first value is the change on the x-axis and the second is the change on the y-axis. So here we’re telling the background to move 120px to the left and not change on the y-axis, which will show the second half of our background image.











5 Comments