Jun12
Browser compliant reusable image rollovers with CSS
- posted by: Bruce
- 4 comments
- post a comment
Months ago when working on development for RMI | BET’s video website I needed a way to do image rollovers but I didn’t want to have a reliance on javascript. So, I set out to a create a reusable image rollover solution that was completely CSS based. Basically the concept was to have a universal class that could be called at any time in the HTML to create a rollover image.
Since first creating this code I’ve integrated it as a standard into all of our starting CSS templates.
Here’s how this works:
Start out with a basic anchor tag and give it a class of “hover-box”. Then inside the anchor tag add both images, your original and your hover version. Place the hover image first in the tag, and then add the original one second. Add a class of “hover” to the hover image. It should look like this:
<a href="#" title="Link title..." class="hover-box">
<img src="rollover-image.jpg" class="hover" alt="Rollover"/>
<img src="original-image.jpg" class="original" alt="Original"/>
</a>
Now, make sure this CSS is included in your document.
a.hover-box img.original { /* required for IE6 */
float: left;
position: relative;
}
a.hover-box img.hover {
display: none;
}
a.hover-box {
position: relative;
float: left;
display: block;
}
a.hover-box:hover {
display: block;
font-size: 100%;
z-index: 1;
}
a.hover-box:hover img.hover {
display: block;
position: absolute;
left: 0;
top: 0;
z-index: 1000;
}
Okay, basically this is hiding the hover image to begin. Then, once the anchor tag is hovered over the image with class “hover” displays itself as block and is positioned absolutely directly on top of the original image. This is accomplished because the hover-box class is set with relative positioning, meaning that the hover image is tied to its boundaries.

Bang! There you have it, a simple CSS hack-free solution that works in: Firefox, Safari, IE 6 & 7, and presumably all other standards compliant browsers. Check it out in action…
P.S. This is especially sweet because the image is preloaded and then hidden, meaning the hover effect is instant for the viewer.
Edit: After some testing I found out my original version wasn’t always working in IE6. It seems that for some reason IE6 needs a class applied to the original image that floats it and positions it relative. I tried every possible way and this is the only thing making it work without a * hack. Not a huge deal though. Also, IE6 requires the original image to come second in the HTML, unlike I originally thought.











Leave a comment