Ramin Hossaini

Smart Menu-Hover

Mar
18

When making a navigational menu or button of some sort, you might have an image for the normal state (a:link), the hover (a:hover), the active state (a:active) and even one for the visited state (a:visited). Usually, you would have an image load for each one like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#nav a:link
{
background-image:url(menu.jpg);
}
 
#nav a:visited
{
background-image:url(menu.jpg);
}
 
#nav a:hover
{
background-image:url(menu_hover.jpg);
}
 
#nav a:active
{
background-image:url(menu_active.jpg);
}

The browser would only load these images when these states have been activated. This would mean that the first time a user moves his mouse over the menu it wouldn’t show anything different from the a:link background-image until the a:hover image loads.

There’s a simple trick to get around this. Say you have a menu image like the this, you might want the first part to be the a:link and the 2nd part below it would be the a:hover background-image.

Menu-pattern

In your CSS, you would use only 1 image (like the one one above). However, you would use a different background-position for each state:

1
2
3
4
5
6
7
8
9
10
11
12
13
#nav a:link
{
background-image:url(menu.jpg);
background-position:0px 0px; /*Use first part*/
}
 
...
 
#nav a:active
{
background-image:url(menu.jpg);
background-position:0px -98px; /*Use 2nd part*/
}
Menu-pattern-detail

The -98px in the CSS comes from the dimensions of the image. This means that the image is loaded when the page is loaded, and thus, it also means that there is no loading for the other link states.

This method can be extended to work with the visited and active states too.

2 Responses to Smart Menu-Hover

  1. This is great because Internet Explorer has a bug which doesn’t cache background-images so they flicker all the time. I used this for my website.

  2. Glad it was useful Willem 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *