While scoping for a new designer I recently read through over 50 resumes and consequently looked at over 50 online portfolios. What struck me as frankly surprising (shocking) was the high number of designers who still use oodles of JavaScript to create a simple image hover effect, usually in the navigation.
I have a simple rule: If it can be accomplished with CSS, then do it with CSS. Unless it breaks standards or semantics of course. So here is my simple tutorial preserved for prosperity in the hope it will one day reach the right people.
How it works
We are going to use a single image to create 3 buttons states: default, hover and active. Basically we are going to position the background image for each state with CSS. The image (button.gif) I've created for this tutorial looks like this:
![]()
The dimensions of this image are critical, in that all 3 states need to be the exact same width. Each button state in this example is 120 pixels wide, which means we also have to make it known in the CSS.
Start with a simple menu list like...
<ul id="menu">
<li><a href="">Item 01</a></li>
<li><a href="">Item 02</a></li>
<li><a href="">Item 03</a></li>
</ul>
...with this CSS.
#menu li {
list-style:none;
text-align:center;
float:left; /* Remove this float if you prefer a vertical menu */
}
#menu li a {
width:120px;
height:30px;
padding:10px 0 0 0;
display:block;
background-image:url(button.gif);
background-position:left;
text-decoration:none;
color:#fff;
}
Notice we have positioned the background image left for list items which are 120px wide, which means only the left (blue) part of it will be visible.
Changing states
Now we want to change the position of the background image for 2 more states, hover and active. Add this CSS:
#menu li a:hover {
background-position:center;
}
#menu li a:active {
background-position:right;
}
Now when you hover over a menu item the background position shifts to the center showing only the green section, and when the mouse is active the background position shifts to the right to only show the orange section.
Too easy huh? Test it out for yourself here.
Why one image and not three?
The exact same effect can be achieved with 3 separate images, but each would have to be referenced accordingly in each of the 3 CSS states, but using a single image is better because it means you only have one http request as opposed to 3.
button_states.zip (8k)


Davo
A good lesson to those still using MM Script
Sunday 31st May 2009 | 10:04 AM Reply Comment URL Back to top