CSS Image Rollovers with No Javascript

Up until recently I have always relied on javascript to create image replacement and
image rollover techniques and haven’t really thought about alternatives. As far as I was
concerned javascript was just the way it was done.

The problem with javascript is that the rollover image has to be preloaded for it to
create a smooth effect and it doesn’t work in all browsers, especially with many people turning javascript support off for security reasons

This is why I have been converted to the use of CSS for all my image rollovers from now on.
They are supported in any browser that renders css and they even work with javascript disabled creating an instant smooth effect

OK, enough with the background lets look at an example CSS image rollover:

So how is it done?

Start by preparing your image for your rollover, I have used photoshop CS2 but you can create the image with any image editing software.

First of all create the standard button with these settings

I have filled in the background and applied a gradient, added text with a bevel and a small bike graphic.

When you have finished creating the standard button, group it into a folder then increase the size of your canvas to double it’s width, such as:

You should end up with a canvas similar to this:

Now duplicate your group and position it to the right of your standard button graphic

Make changes to the second group, this will act as the rollover state

Here I have changed the background gradient and used a colour overlay on the bike graphic

You should end up with an image similar to this

Save it for the web, I have saved as a png

Lets make it work

Armed with our prepared rollover image it just takes a simple bit of coding to get it working

Place the following html inside the <body> tag where you want your rollover to appear.


<a class="my-rollover" target="_blank" href="http://www.iwanttoridemybicycle.co.uk"></a>

Then in your stylesheet add the following style for my-rollover, make sure you change the background-image url to point to your own rollover image


.my-rollover {
  display: block;
  height: 25px; width: 100px;
  border: solid 1px black;
  background-image: url('Images/Btn-Bikes.png');
}
a.my-rollover:hover { background-position: -100px 0; }

This will set up the a tag to only show the first 100px of your image. When the mouse rolls over the image the :hover style will move the background image 100px to the left which brings your over state into view. No javascript, no preloading, no mess, what more could you want in a rollover?

This technique can be modified for any size of image, just change the height, width and background-position values

This technique was introduced to me by Rob at Swansea Digital Web Design

February 24th, 2009 | 1 Comment

Powered by WordPress | Blue Weed by Blog Oh! Blog | Entries (RSS) and Comments (RSS).