CSS Sprites for Image Rollovers

A while ago I wrote a small post on how I had used the CSS style of display: none in order to hide images that I had used for rollover.  A commenter had said this was the wrong way to do this and using CSS sprites was the best method.  Having done some research here is what I have come up with in using CSS sprites for image rollovers.

I first wanted to use them when I had a background image on a particular element and then I wanted this to change when the mouse was hovered over the item.  This is easily done with background-image in CSS.  The problem is that the hover image is only loaded on hover and therefore there is a short delay in the loading on the image which looks messy.

To get around this instead of using 2 separate images for the background images we can use the same image but show different parts of the image on hover and the normal view.

When the page loads the part above the orange line is the part that the visitor sees, then the part below the orange line is the bit that the visitor sees when they hover over the image.  There will be no delay in the hover effect because this image is loaded as the background image for this element on page load with the CSS file.

Lets imagine that these effects are needed on a list of links.  The grey gradient is required on each link in the list and on hover this turns green.  Therefore the HTML on the page may looks something like this:

[code language=”html”]

[/code]

The CSS that would be needed in order to make this work with CSS sprites for the hover effect would be the following:

[code language=”css”]
ul.links li a {
width: 220px;
height: 85px; /* how far down the image you want the background to extend */
display: block;
background-image: url(images/linkbg.jpg); /* the url of the image to be used */
background-position: 0px 0px /* this ensures the image starts showing in the top left corner */
background-repeat: no-repeat;
}
ul.link li a:hover {
background-position: 0px -100px; /* the second value sets how far down the image your hover image starts */
}
[/code]

So happens here is that the area that is visible in the background image changes with the hover CSS rule to moving down the image 100px, which means on hover only the bottom 100 pixels are shown and the top part is hidden.

As well as preventing the problems of pre loading the image this also reduces the load on the server because only 1 server request is made instead of two as the image for the background is called one and CSS does the rest!

Why not give it a try and let me know how you get on.

Leave a Reply

Your email address will not be published. Required fields are marked *