How To Create A Rollover Button
A rollover button provides an eye-pleasing option to your site as an alternative to a standard hyperlink. When a user hovers their mouse over the button image it magically changes – a great party trick to impress all your friends!
There are a variety of methods for doing this but we’re going to show you the cleanest, most browser-friendly option. A small caveat, however: while this method generally works fine on modern computers (from the last five years or so), you may find it a little hit-and-miss on anything older, so be cautious.
There are three aspects to this process:
- Creating the image
- Adding the HTML to the page
- Adding some new styles to the CSS file
Step 1 – Create the image
What you need to do is create a single image that includes your button in its normal state as well as its rollover state; the final image will be exactly twice the height of the button size.
For example, if your button size is 100 pixels wide and 20 pixels high, then the image you are creating will be 100 pixels wide and 40 pixels high.
Step 2 – The HTML
We simply insert a search engine friendly hyperlink in the code, as shown here.
<a id=”clickMe1″ href=”somepage.htm”><span>Click Me</span></a>
It is important we give the link a unique ID, as in this example it is clickMe1. This is particularly important if we are adding more than one rollover button. The second button will be clickMe2 etc. The reason for this will become obvious in the next step.
Step 3 – Adding the CSS
This is where a little bit of CSS magic comes in to play and transforms our ordinary looking hyperlink into a super impressive rollover button.
Add the CSS code shown here to your CSS style file, replacing clickMe1 with the ID you have used as well as updating the image file name. If the image isn’t stored in the same folder as your CSS file then add the full URL.
#clickMe1
{
display: block;
width: 100px;
height: 20px;
background: url(“clickme.gif”) no-repeat 0 0;
}
#clickMe1:hover
{
background-position: 0 -20px;
}
#clickMe1 span
{
display: none;
}
You should also change the “width” and “height” so that it’s the same width and height as your button. Remember that you’ve made your original image twice as high as your actual button, so your “height” number should be half the height of your image.
Lastly, look at the part that refers to background position, as shown here.
background-position: 0 -20px;
Substitute -20 with the number you just used for “height”, with a minus in front of it. So if the total height of your button is actually 60 pixels and not 40 as we’ve used in our example, then change it to what’s shown here.
background-position: 0 -30px;
Save the changes to your CSS file. That’s it – you’re done!
Lesson Summary
In this lesson we looked at how you can easily make a rollover button that works on multiple computers. The three steps were:
- Creating the image
- Adding the HTML to the page
- Adding some new styles to the CSS file