Image rollovers using just CSS
Image rollovers can prove an effective way to make links and buttons more intersting and aesthetically pleasing. Most techniques reply on javascript and while it works it results in a lot more code necessary and usually doesn't work as seemlessly as desired. We can use CSS to replace the javascript to provide quick and easy rollover images for links. We'll be using a single image so there is no need to worry about preloading the hover images and intgeration is far more seemless than the equivalent javascript.
In this tutorial we'll create a comment link which will include a simple image rollover. While this is admittedly a trivial example the techniques used can be applied to create image rollovers of almost any kind.
The image
First step in this tutorial is to create the image. Unlike "old style" rollovers where we had a normal and hover image, this CSS technique relies on both of the images put together, above and below or side by side like the examples below:
Vertical setup:
Horizontal setup:

The HTML
<a href="#" class="rollover"><span>Comments</span></a>
The HTML is just a standard link - the only slight difference is that a span is used to wrap the link text. This will be used later to hide the comment text as the image itself contains the text.
The CSS
Firstly we set up the CSS for the link:
a.rollover {
background:url('css-hovers-comments.png') no-repeat top left;
display:block;
height:36px;
width:175px;
}
We use the background property to set the background image to that of our rollover image. Setting display to block means the link will fill the full size of the link as specified by the height and width properties. The height of the link is set to half the size of the image. This means only the top half, the "normal" image, is shown. The output of this CSS applied to the above HTML gives us our link:
CommentsNow the problem is that our link text is messing with the image. We add a bit more CSS to hide this text - this is why the span is present in the HTML:
a.rollover span {
display:none;
}
Now our link looks like this:
CommentsThis means the text is hidden to the user but still exists for spiders and screen readers - making the links accessible and SEO friendly.
The CSS rollover
Lastly we add the rollover effect this is done by adding a little bit more CSS:
a.rollover:hover {
background-position:left -36px;
}
This has the effect is moving the background image upwards by 36 pixels on hover. This results in the second half of the image, the "hover" image, being displayed. The final link is shown below:
HelloThe final code
<style type="text/css">
a.rollover {
background:url('css-hovers-comments.png') no-repeat top left;
display:block;
height:36px;
width:175px;
}
a.rollover span {
display:none;
}
a.rollover:hover {
background-position:left -36px;
}
</style>
<a href="#" class="rollover"><span>Comments</span></a>
