CSS rollover images

Rollovers can be done a few ways, some of which work and some that have issues. This tutorial will show you a great way to do pre-loaded CSS button rollovers.

Example.

Download that ugly button image and save it into a folder you want your web page to be. Notice that all the button states are saved into 1 image.

The position of each button in the image doesn’t matter at all, you can have them in any order, going horizontally if you prefer, they can even me positioned randomly over the image or contain graphics for all your buttons if you want. The main thing is is that you keep all the button states the same width and height.

Next is to make a HTML page with the button in it. Save this as your index.html (or whatever you like):

<html>
<head>
 <link rel="stylesheet" href="screen.css" type="text/css" />
</head>
<body>
 <h2>Awesome Button</h2>
 <p>Click the button below to go into outer space</p>
 <form action="#" method="get">
   <input type="submit" value="" id="awesome_button" />
 </form>
</body>
</html>

I gave the button no value so it doesn’t display text on it.

Then make a CSS file and save it into the same folder as your index file.

#awesome_button {
 background: transparent url('ugly_button.gif') no-repeat scroll 0 0;
 width: 133px;
 height: 33px;
 border: none;
}

Take a look at the button. Pretty sweet. But how do you get it to change when you hover over it? Simple, add this into your CSS file:

#awesome_button:hover {
 background-position: 0 -32px;
}

All this does it tell the button’s background to shift up 32 pixels, and because we gave the button a width and height, you won’t see the rest of the image. And because all the button states are loaded all at once, you don’t get a half-second delay as the browser loads your hover image like it would if you had separate images.

And finally, the active state:

#awesome_button:active {
 background-position: 0 -64px;
}

You can also make it display the little hand mouse pointer by changing your hover code to:

#awesome_button:hover {
 background-position: 0 -32px;
 cursor: pointer;
}

Simple right? Unfortunately this method doesn’t work in IE6. If anyone knows of a way of getting it to work then feel free to leave a comment, or just leave a comment if you have any tips or questions.

Post to Twitter

One Response to “CSS rollover images”

  1. Matthias says:

    It doesn’t work in IE6 because IE6 only supports :hover on links, not on inputs. Google for ‘IE6 hover fix’.

What does your brain think?