CSS Magic

January 24, 2006

Sprite Based Navigation

Filed under: (X)HTML, CSS — Steve Frost @ 9:06 am

Using only a simple unordered list, a single image and some CSS, we will create a site navigation bar that is aesthetically pleasing, quick to load and accessible.

The Code

First we start of with some basic code
<ul id="navbar">
<li id="navitem1"><a href="#"></a></li>
<li id="navitem2"><a href="#"></a></li>
<li id="navitem3"><a href="#"></a></li>
<li id="navitem4"><a href="#"></a></li>
</ul>

The Image

Next we have to create an image to use for the navigation.

As you can see from the image, you need to create is one single image split in to a grid, one normal button and a hover state for each list item, in this instance each button is 100px wide and 35px high.

The CSS

First off, the CSS to provide the basic layout for the list and apply the background image
#navbar {position: relative; width: 400px; height: 35px; background: url(nav.gif); margin: 10px auto; padding: 0;}
#navbar li {position: absolute; top: 0; margin: 0; padding: 0; list-style: none; }
#navbar li, #navbar a {height: 35px; display: block;}
#navitem1 {left: 0; width: 100px;}
#navitem2 {left: 101px; width: 100px;}
#navitem3 {left: 201px; width: 100px;}
#navitem4 {left: 301px; width: 100px;}

So far, so good. We have a navigation bar, as you can see from the CSS above we have set the size of each list item and then applied a background image, by off setting the image using the left property, we have applied a different image to each list item, now lets add some hover states to it.
#navitem1 a:hover {background: transparent url(nav.gif) 0 -35px no-repeat;}
#navitem2 a:hover {background: transparent url(nav.gif) -101px -35px no-repeat;}
#navitem3 a:hover {background: transparent url(nav.gif) -201px -35px no-repeat;}
#navitem4 a:hover {background: transparent url(nav.gif) -301px -35px no-repeat;}

Ok, are you still with me?
At this point we now have a working navigation bar with hover states, which works wonderfully in web browsers, if you wish to also provide text links for accessibility reasons, just remember to use your favourite image replacement technique to remove them later.
but what else can we do?
How about we add some CSS to make the relevant button change to it’s hover state depending on which page is loaded.

First thing we need to do is make sure that we have an ID in the body of each page for example.
<body id="nav1">

Then we add the following CSS
body#nav1 #navitem1 {background: transparent url(nav.gif) 0 -35px no-repeat;}
body#nav2 #navitem2 {background: transparent url(nav.gif) -101px -35px no-repeat;}
body#nav3 #navitem3 {background: transparent url(nav.gif) -201px -35px no-repeat;}
body#nav4 #navitem4 {background: transparent url(nav.gif) -301px -35px no-repeat;}

And, we are finished if you take a look at this example you can see the finished navbar in action.

Blog at WordPress.com.