Rob Ewaschuk's Blog : /life/sabbatical/a-novel-pure-css-image-rollover-technique.html Rob Ewaschuk

Site Sections

/life/sabbatical/A (Novel?) Pure CSS Image Rollover Technique

CSS:

a.rollover { background: no-repeat -9999px -9999px; display: block; }
a.rollover:hover { background: no-repeat top left; }
a.rollover:hover img { visibility: hidden; }

HTML:

<a class="rollover" style="background-image:url('blog-roll.png')" href="/blog">
<img border="0" alt="blog" src="blog.png"/>
</a>

This is a variant on other techniques I found. By setting the a tag to be a block-level element, it gets the size of the contained image; by setting the background by offsetting it, you get preload; by setting the foreground but using visibility:hidden (as opposed to display:none) it keeps its size. You also get a single point of truth for the button: image, rollver image and alt tag are all in the same place. Finally, this works everywhere I tested it (Safari 3.1.2; Firefox 2 and 3; IE6 and 7).

There are a few gotchas: don't be lazy and set background instead of background-image in the style tag, because that sets the other background CSS back to the default, specifically repeat:repeat. The images need to be the same size, pretty much. If you haven't cleared borders around images, they might be a problem, too.

I dunno if this is actually novel, but I didn't see it as I looked around. The (IMO less natural and more fiddly) technique of using a single image and changing the offset seems to be more popular.