Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Using CSS to create rollovers

Rated 4.15 (Ratings: 31) (Add your rating)

Log in to add a comment
(20 comments so far)

Want more?

 
Picture of simonc

Simon Coggins

Member info | Full bio

User since: September 03, 2001

Last login: September 03, 2001

Articles written: 1

Since the introduction of the image object in Netscape 3, web designers have been using text in GIFs and JavaScript to create graphical navigation bars. For a long time this was the only way to achieve this eye-catching effect, but finally increased support for the CSS1 spec is beginning to change the situation. It is now possible to create light, functional, standards-compliant equivalents to JavaScript rollovers using nothing more than HTML and CSS1.

To show you what this might look like, the link below shows a navigation menu for a fictional pizza delivery company. In order to see the example below correctly you will need a browser with good CSS support, such as Internet Explorer 5+, Netscape 6, Mozilla or Opera 5.

Click here to view the example
(opens in a new window)

Advantages

As you can see, the CSS menu shares much of the same appearance and functionality of the JavaScript version. It also benefits from several important advantages:

  • File size
    Graphically-generated rollovers usually add significant weight to the overall file size of a page. Two sets of GIFs for each button, plus the associated JavaScript code seems excessive for what is essentially nothing more than a list of links. Download time is of particular importance for a menu bar used for navigation, since any delay to the appearance and functionality may cause disorientation for your visitors.
  • Accessibility
    Plain text is generally more accessible than images. It can be read by all types of browsers and easily indexed by search engines. Additionally using CSS prevents the need for JavaScript (which is not universally supported) and allows control of pseudo classes such as :visited and :active to provide further navigational clues.
  • Maintainability
    Adding links or making changes to a graphical navigation bar can be a lot of trouble. Even the simplest alteration requires the editing of images and/or JavaScript code. With the CSS method, changes to the text are as easy as editing a link, and site-wide changes in appearance can be implemented simply by editing the global stylesheet.

Disadvantages

Too good to be true? Well, sort of. There are a couple of obvious disadvantages to using this approach over the classical JavaScript rollover:

  • Font styling
    When creating graphical rollover images, you have access to a wide range of fonts and effects. Using CSS your choices are much more restricted, since you are relying on user-installed fonts and CSS font styling effects.
  • Backward compatibility
    As mentioned above, the CSS method only functions correctly for a limited range of browsers. Even so, roughly 85% of your audience should see the CSS menu in its full glory, while the rest are served a simple but usable list of links (see below for more on backward compatibility).

How it works

So, hopefully I've convinced you of the benefits of this new method, let's take a look at how it's done. We'll begin by taking a look at the HTML required:

<div id="navi">
   <div>
      <a href="#">Express Pizzas Home</a>
   </div>
   <div>
      <strong>Online Pizza Orders</strong>
   </div>
   <div>
      <a href="#">Our Delivery Promise</a>
   </div>
   <div>
      <a href="#">Special Promotions</a>
   </div>
   <div>
      <a href="#">Contact the PizzaMaster</a>
   </div>
</div>

"That's it?" I hear you cry. Well, almost. Just slot it in where you want the navigation and update the links. We've included our list of links, with each entry enclosed in a DIV so that it appears on a new line. The current page is wrapped in a strong tag, to make the current location clear. The whole thing is then wrapped in another DIV with an id of navi, so that we can manipulate the elements with CSS in our stylesheet.

Linking the stylesheet

In order to style the elements of the navibar, we need to link to our global stylesheet. Unfortunately, the CSS required is not correctly implemented in browsers before version 5, so we need to hide this stylesheet from older browsers to prevent them from breaking the page. This can be achieved using the @import syntax. Include the following code in the HEAD of your page:

<style type="text/css">
<!--
@import "navibar.css";
-->
</style>

This is a very important step! Including the navibar style in a standard linked stylesheet will break the page badly in Netscape 4 and Internet Explorer 3 and 4. In Netscape, users won't even be able to click on the links! Of course, it is still possible to link to another stylesheet as well as this one, by including additional statements in the document HEAD.

The Stylesheet

So now we've written the HTML and included the stylesheet, let's take a look at the CSS required to wrap things up. Here's what the stylesheet navibar.css looks like:

#navi a , #navi strong {
	color: #000;
	font: 12px Arial,Helvetica,sans-serif;
	text-decoration: none;
	border: 1px solid #000;

	display: block;
	width: 162px;
	padding: 3px 5px;
	margin: 7px;
}

#navi strong {
	font-weight: bold;
	background: #DDD;
}

#navi a {
	background: #FFF;

}

#navi a:hover {
	background: #999;
}

The stylesheet is divided into four declarations. The first applies style to both the anchors and the strong tag. The second and third add additional styles to those elements separately. The fourth declaration is for the "mouse-over" state of the anchors.

The statement that give the CSS navigation bar its functionality is display: block;. It converts the &lt;a&gt; and &lt;strong&gt; tags from inline elements to block-level elements, which allows them to be treated as solid rectangular boxes. These boxes can then be assigned a size and styled using other CSS statements.

Backwards Compatibility

Because the HTML required is very straightforward the result is, naturally, backwards compatible degrading to a simple list of links:

Express Pizzas Home Online Pizza Orders Our Delivery Promise Special Promotions Contact the PizzaMaster

Of course, this might not be ideal under certain circumstances, so here's an alternative way of coding the navibar for backwards compatibility. Change the HTML to the following:

<div id="navi">
   <a href="#horz">Express Pizzas Home</a>
<span class="hidden">|</span>
   <strong>Online Pizza Orders</strong>
<span class="hidden">|</span>
   <a href="#horz">Our Delivery Promise</a>
<span class="hidden">|</span>
   <a href="#horz">Special Promotions</a>
<span class="hidden">|</span>
   <a href="#horz">Contact the PizzaMaster</a>
</div>

Then add the line span.hidden { display: none; } to the stylesheet. This will display the navibar as a horizontal list of links separated by a vertical bar:

Express Pizzas Home | Online Pizza Orders | Our Delivery Promise | Special Promotions | Contact the PizzaMaster

By setting the style of the | symbols to display: none, they will be hidden completely from the full version of the bar, which will appear the same as it did before.

Customisation

For this article, the code has been kept extremely simple for the purpose of clarity. Using the full power of CSS there are many possible additions that can be made. Here are a few ideas for some additional changes to the basic code:

  • Use of background images
  • :visited, :active and :focus states with different styles
  • Other CSS text styling (text-align, letter-spacing, border decoration)
  • Use of the title tag within the anchors to provide tool tips that give additional information on each link
Simon is currently studying for a Ph.D. in Astronomy at the University of Nottingham, England. He is interested in most aspects of Web Design, including front-end and back-end coding, usability and information architecture. He created the evolt.org directory and continues to maintain the link database.

The box model hack

Submitted by simonc on October 29, 2001 - 03:40.

One thing that I didn't mention in this article is the IE5/Win Box Model bug. It will cause a small inconsistency in the width of the buttons in IE5 for Windows, rendering them slightly smaller than in other browsers. Usually this is only a small effect (a few pixels), but if you require pixel perfect control you can fix the problem using this Box Model Hack.

login or register to post comments

GO CSS GO!

Submitted by maxgruv on October 29, 2001 - 11:04.

Excellent article. The power of CSS-1 alone amazes me! It's good to know we have an easy alternative to using bulky scripts and images for simply producing a few "cool effects." Now if we can just rid the world of Netscape 4...

login or register to post comments

Additional CSS property and attribute

Submitted by krr on October 29, 2001 - 20:46.

I read an article written by Eric Meyers about a year ago where he showed how to use the image background-propery on the hover attribute in your style sheet. Very cool effect. Draw back of course was that it only worked in IE 5+ and possibly in NN 6. But to be able to use CSS in stead of the javascript mouseover was very cool! Kevin

login or register to post comments

Love that 'a:hover' pseudo-class

Submitted by StOne on October 29, 2001 - 22:06.

In my CSS I usually put something like:

a.:link { color: #0000ff; text-decoration: none }
...
a.:hover { color: #ffffff; text-decoration: none; background-color:#0000cc }

for a nice little mouseover effect.

For browsers that do support the a.:hover pseudo-class (namely IE, used by the vast majority), you can get some very cool effects very easily.

login or register to post comments

Tried the back-ground image attribute in

Submitted by krr on October 29, 2001 - 23:24.

Have you tried the background-image attribute in the hover class, Instead of the back-ground: color attribute? You don't need to use the to make it work. Kevin

login or register to post comments

Re: Additional CSS property and attribute

Submitted by luminosity on October 30, 2001 - 00:00.

Eric Meyer has a new one up too. Hidden text that appears on mousing over a link (as a sort of navigation aid), in the same box for all links, and another example to go with that, of using images in place of the text.. very cool.

login or register to post comments

Thank You

Submitted by krr on October 30, 2001 - 01:14.

I appreciate the insight. Thank You Kevin CSS rocks!

login or register to post comments

check this out.

Submitted by komlenic on October 31, 2001 - 04:09.

You might want to check out this section of Eric's site: css/edge. Very cool stuff.

login or register to post comments

What's new about it ?

Submitted by skamp on October 31, 2001 - 08:00.

I'm sorry, but what's new about that ? W3 has been using this effect on its site for months... and I don't even mention Microsoft... Am I missing something here ?

login or register to post comments

Not new, but still useful

Submitted by simonc on October 31, 2001 - 09:26.

Skamp,

It was not my intention to suggest that this technique was particularly new or innovative. I was just trying to explain some of the concepts behind this approach and give a real-world example that could be taken away and used. As support for CSS1 improves, now seems like the right time to showcase some of the features of Cascading Style Sheets to designers who may not fully aware of what it can do (or indeed how to do it).

login or register to post comments

Well Writen

Submitted by steveg on November 8, 2001 - 13:49.

Simple, straight-forward, thorough...thanks

login or register to post comments

Cool

Submitted by mpgnet on November 11, 2001 - 20:10.

Man, that's pretty sweet! THANKS! -

login or register to post comments

aaaah!

Submitted by yafujifide on November 12, 2001 - 19:37.

i was all proud of myself for discovering this amazing technique, and now i see there's an article about it out there! ah well... i'll discover something cool for real eventually...

login or register to post comments

CSS & IE 6?

Submitted by haidary on December 11, 2001 - 18:20.

Do you guys have compatability issues when using CSS in IE 6? It seems to me like Microsoft forgot to include alot of CSS features when developing IE 6. I can hardly get anything to work right. The example in this artical works perfect though. Great work. Nice, clean artical.

login or register to post comments

CSS & IE 6

Submitted by komlenic on December 11, 2001 - 18:27.

haidary, No browser gets all of the CSS spec correct, but most current versions do reasonably well... if you're attempting some of the more advanced stuff...Mozilla is probably the only browser that will be able to handle it. For what it's worth, IE 6 isn't too bad, you just have to start small (fonts colors etc.) and keep trying things and making sure they work. Test, test, and test again...good luck.

login or register to post comments

Good Job!

Submitted by oiboi on January 9, 2002 - 18:25.

Hey... thats a great job on explaining something that not a lot of people use!

On the comment earlier about the a:link{} / a:hover{} "psudo-class" If you notice how simonc uses it in the article.

.header {font-size=11}
.header a:link {font-size=12}
.header a:hover {font-size=12; bgcolor=#FFFFFF}

You can make different colored links all over the place without and font tags! Its a great time/bandwidth saver.

And uh... skamp... ya... this isnt for new technology.... its for people new to the technology. Just be appreciative!

login or register to post comments

With JS.

Submitted by haidary on January 10, 2002 - 00:44.

Putting accessibility aside for a second, I would like to point out you can get the same rollover effects that have two of the three advantages of using pure CSS. I feel that if accessibility is not an issue, that the following way is much easier to deal with (Just my personal opinion though). Instead of trying to explain what I do I'm just going to show you an example of the code. You can use this same method with all page objects. In fact this text area has an onClick and onMouseOut done the same way. Try it. If you don't see a BG color, than your browser doesn't support it.

CSS Test Page Link One
Link Two
Link Three

I realize in a lot of cases this would not be the best way to do things, but for my personal site, it sure makes my life easier.

login or register to post comments

Oops...sorry.

Submitted by haidary on January 10, 2002 - 00:55.

I appologize for my last post. It didn't work like it was suppose to. If you want to view the example you can click the link below.
Yup...This Link.

login or register to post comments

totally random

Submitted by tuhtest on June 25, 2002 - 07:26.

simonc is a hottie! (i came here with genuine geek interest ... too bad none of this works in nn).

login or register to post comments

Lists?

Submitted by wodeh on March 16, 2005 - 08:25.

Should not lists of links be presented within actual LISTS, definition lists, unordered lists or ordered lists depending on what you want to do with them?

This maintains the semantec HTML and eliminates an awful lot of superfluous div elements which are really intended for grouping more than one child element together into logical groups which can then be laid out using CSS.




or

Link One
A link to somewhere
Link Two
A link to somewhere else

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.