CSS Rollover Images

by | Mar 9, 2010 | CSS, Tutorials

Image rollovers are fun and can add both life and functionality to a web page. Most often they are used in menus but we find they are useful for hyperlinked images as well. This is a simple tutorial on how you can create fast loading rollovers throughout your website giving it that slick look.

Methods

There’s 3 basic ways you can create a rollover effect:

Flash animation

Javascript

CSS

 

For our purposes we’re going to skip the first two and use strictly CSS and a tad bit of HTML to make it all work. We’re going to be using a sprite in order to accomplish this. If you don’t know what a sprite is it’s basically a single image with all of your different colored effects self contained. The fact we use a single image means that there’s no additional preloading that has to be done which, when using multiple images, can cause a flicker or pause in the initial display of the mouseover event. Here’s an example of a sprite image which consists of two identical designs but with different colored backgrounds:

The goal here is to use this image in a rollover event for a hyperlink.

CSS

Here’s the CSS Code we’ll be working with:


#imageLink
{
  display: block;
  width: 200px;
  height: 40px;
  background: url("compare-sprite.jpg") no-repeat 0 0;

}

#imageLink:hover
{
  background-position: 0 -40px;
}

#imageLink span
{
  display: none;
}

First, keep in mind that we are creating a hyperlink. Therefore we are going to utilize this code when we create our link by assigning the id to the hyperlink like you would a class. We’re going to explain the code just a bit.

  • the height and width represent the single button, not the entire image. So, if the entire image is 80px tall and divided perfectly between the two versions then we set our height at 40px.
  • On the :hover we want the background position to move down 40px. Therefore we set the position to -40px to make the effect. Same image, just showing a different portion of it.
  • The use of the span tag is to complete our hyperlink since the background image isn’t really creating a link. Therefore, something tangible has to be there. But, the trick is, we set the display to none which makes it invisible to the viewer and all they see is the image

The HTML

Here’s the HTML:

Some text here

You can have as many rollovers on one page or throughout your site as you wish using this code. But, you have to copy the code and assign each one its own unique ID. And, of course, their own images if applicable.

0 Comments

Pin It on Pinterest

Share This