Home / CSS Sprites – making one of the buttons active

CSS Sprites – making one of the buttons active

A few months ago I posted using CSS sprites for image navigation which looks at how to use a single image for navigation; when the mouse moves over the background position is changed and some effect happens e.g. the background color changes. I recently received an email asking how to make one of the buttons active/selected so have written this breif follow-up post covering this.

CSS sprite example

Please refer to the original post to see an example of the CSS sprite image and the actual effect working. The full HTML and CSS for the example is covered in that page.

Making a button active/selected

All that is required is to add a class to the button that should be currently active. On my sites I usually call it something like .selected and add in on the server-side with PHP, but it could easily enough be done after the page loads with Javascript or a Javascript library such as jQuery or Mootools.

In my original example the HTML for the home button looks like this:

<li><a id="example-nav-home" href="#">Home</a></li>

and the CSS looks like this:

#example-nav-home {
    width: 42px;
}
#example-nav-home:hover {
    background-position: 0px -26px;
}

Modify :hover to include the .selected class like so:

#example-nav-home:hover, #example-nav-home.selected {
    background-position: 0px -26px;
}

and then when it’s the homepage add the .selected class to the <a> tag:

<li><a id="example-nav-home" class="selected" href="#">Home</a></li>

Then it’s just a matter of adding the necessary code to mark the selected one.
I’ll leave that part up to you 🙂