This is a simple, pure CSS image roll over technique that you can use on your next design project, e.g. a button rollover. This technique can also be used to do a before and after effect on an image on mouse-over, like in my example.
The first thing you need to do to create a rollover is your before and after pictures, or mouse-off and mouse-over pictures. Merge the images into one document with your favourite image editor, with your ‘before’ picture first, and your ‘after’ picture below it. In my example the picture is 324 pixels wide and 400 pixels high. So in total that would be 800 pixels in height. Here is the full image that I use.
Now for the code. First we setup the CSS with a container for the before and after image we want to display:
.swap span { display: block; width: 324px; height: 400px; background: transparent url(beforeafter.jpg) no-repeat; } .swap span:hover { background-position: 0 -400px; }
And in our HTML we put this piece of code:
<div class="swap"> <span> </span></div>
Edit: To make it work properly in IE copy the following code into your site’s header:
<!--[if lt IE 9]> <script type="text/javascript" src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"> </script> <![endif]-->
The ie7-js library makes MSIE behave like a standards-compliant browser.
An explanation: The first piece of CSS creates the span container to display only the before and after image, not both. Thus it has a height of a single image, 400 pixels.
We then add a span:hover so that something happens when the mouse hovers over the image. What happens is this: The background position of the image gets shifted 400 pixels upward, i.e. the first ‘before’ image gets shifted up and away, and only the second ‘after’ image shows.
This technique is often called the CSS sprite method. Have fun.