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:
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.
- The typical javascript approach: using the onMouseOver and onMouseOut events to swap the images.
- The typical css approach: an element that sets its background-image attribute to the default image, and changes its background-image attribute to the rollover image when the :hover pseudoclass is activated.
The HTML:<div class="buttonContainer">The CSS:
<img class="rest" src="link_rest.png" />
<img class="roll" src="link_roll.png" />
</div>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.
