Pure CSS rollover for printable images

This is a quickie but may be useful to somebody out there in the big wild interweb.

I had a requirement to implement linked images in a page with a separate rollover image. Normally I’d be using CSS to switch backgrounds but the client wanted the normal image to be visible when the page was printed out. I didn’t want to have to add in javascript, regardless of how simple it would be so I came up with this idea.

The HTML

I’ve used a simple image (<img>) tag contained inside an anchor (<a>) tag to create the link, this ensures that the image will be printed for most default setups.
The anchor tag has a class assigned to be the hook for the rollover and I’ve used an inline style attribute to set the background image of the element to the rollover image. This could also be done by adding a specific class in the stylesheet – but not in this demo.

<a href="#" class="rollover" style="background-image:url(rollover.png);">
 <img src="normal.png" />
</a>

The CSS

I’ve set the display property for the anchor tag to inline-block so that it will sit within the page flow as normal, but takes on the width and height of the image contained inside it.
when the mouse pointer is over the anchor, the visibility property of the contained image is set to hidden, uncovering the the anchor tag with it’s background image.

.rollover{
    display:inline-block;
}
.rollover:hover img{
    visibility:hidden;
}

Example

normal

I’ve tested this on a bunch of browsers – it doesn’t work in IE6 but then, it doesn’t work in Netscape, Mosaic or Lynx either, so go figure.

6 Responses

  1. Lee Kelleher says:

    Nice technique Dave. I also like that this approach handles any image pre-loading too!

  2. kartouche says:

    Brilliant!!! Just what I was looking for – simple, straightforward, no calculations involved. I’m using this for a nav menu applied to elements. :D

Leave a Reply