Jan 16

Simple CSS Rollover with A Single Image [Tutorial]

Posted on Friday, January 16, 2009 in Tutorials, Web Design

This will be our final result using only one image. (you can download exercise files at bottom)

“Rollover me!” -says Mr.Elephant
(you can use any image you would like, not just a super cool elephant and zebra…)

How to do this? LET’S GO!

In simple terms: We are displaying only the left side of the image hiding the right half, then on rollover we are moving the image half way over to display the right side.

1. Create an image twice as wide as the size you’ll need. The left side of the image will be the non rolled over image and the right half will be the rollover part of the image.

Below is the original image.
rollover_image(260width x 108height)

2. Below is the HTML code used, make sure it has a class so our CSS code knows where to look. This will act as our CSS placeholder for the rollover image.

<a class=”imageRollover” href=”#”> </a>

3. Now for the CSS that will do the magic. Let’s get the image to look like we want when nothing is rolled over:

a.imageRollover {
background: url(“rollover_image.jpg”) no-repeat; (This is the image to be used 260×108)
display: block; (this will display the entire image)
width: 130px; (display 130px wide, half the size of our image)
height: 108px; (display 108px high)
text-decoration: none; (This takes off the default styles used on links)

That will display the left half of our image. Now, we want to move our image 130px (half our image width) to the left to reveal the right side when rolled over.

a:hover.imageRollover {
background-position: -130px 0;

This moves our image 130 pixel to the left on :hover (note: background-position: Xposition Yposition)

That’s all there is to a single image rollover in CSS. ENJOY!


Rate this post:
(2 votes, average: 5.00 out of 5)
Loading ... Loading ...