Discussing the nuts and bolts of software development

Friday, June 27, 2008

 

Pure CSS Image Rollover without background-image

The other day I was in a situation where I had an image that changed to another image when the user mouses over it. Usually I will do this in one of two very standard ways:

Unfortunately, neither of these solutions were optimal as I was looking for a pure-CSS solution (so no javascript) and needed the image to have its own <img> tag (so no background-image). After playing around with my selectors a little, I came up with this little gem:

The HTML:
<div class="buttonContainer">
<img class="rest" src="link_rest.png" />
<img class="roll" src="link_roll.png" />
</div>
The CSS:
div.buttonContainer img.roll {
display: none;
}
div.buttonContainer:hover img.roll {
display: inline;
}
div.buttonContainer:hover img.rest {
display: none;
}

This neat CSS trick leaves the images in the html and changes the image on rollover with minimal mark-up. It works by abstracting the :hover pseudoClass to the container, loading both images into the page, and controlling the rollover effect using the images' display attribute.

One word of caution: some older browsers (I'm looking at you, IE6) have poor support for the :hover pseudoclass, which renders this example ineffective; thus if you're supporting a lot of legacy browsers, this may not be for you. However, if you need a rollover that uses actual image tags and want to avoid using javascript, this may be just what you need.

Comments:
I think this sounded clever, so I have tried it in IE 7.
But I cannot make it work.
Can anyone else?
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?