Clips - Css Image Rollovers
Clips - Css Image Rollovers
Many sites out there still use an old JavaScript technique to produce an image
rollover for menu items or buttons. This is bad for many reasons and today
we will learn how to achieve the same effect using CSS.
Before we learn the CSS method, let’s look at the JavaScript rollover and see why it’s a
poor alternative.
Often times developers won’t pre-load all the images and so you end up with a flicker effect
where nothing is shown while a second image loads and leaves the site looking slow and
un-professional.
CSS Method
The CSS method uses what is known as an image sprite to load all the rollover effects as a
single image and we then use CSS to do the transition. To create the image sprite just
create a single image containing all of the individual transitions as shown below.
Once you have your image sprite you just need the HTML and CSS code:
CSS Code
a.rollover {
display: block;
width: 150px;
height: 44px;
text-decoration: none;
background: url("webvamp.jpg");
}
a.rollover:hover {
background-position: -150px 0;
}
.displace {
position: absolute;
left: -5000px;
}
HTML Code
<a href="#" class="rollover" title="Webvamp"><span class="displace">Webvamp</span></a>
Most of this is hopefully understandable, but there are a few things to note:
• The width and height values in a.rollover are the size of the original image.
• The value of background-position is that of the original image width – since we are literally moving from
one part of the image sprite to another.
• We have included a <span> tag with a text alternative to the image and displaced it off the side of the
visible screen so that screenreaders will read it and in the event of no CSS support a text link will be
shown instead.
The following link is the example of a CSS image rollover. You cannot see the example
function unless you have CSS enabled.
Webvamp
Roll your mouse over the button above and see how it instantly changes to the hover
effect. Feel free to also check it out with your CSS disabled to see the text link.
Working It Further
The example above is a very simple example of a CSS rollover. You can develop it further
to provide different transition effects for when the link is clicked or active.Apple.com has a
very good example of this with their main navigation bar.
They include all four states of the navigation bar into a single image and then transition
between them when a user hovers, clicks or views a section.
Update
After Marko’s comment I had added a second post showing you how to make a full menu
bar using CSS rollovers.