HTML rollovers without Javascript

Yes it can be done, you can actually do this without resorting to Javascript, which is just what this short HOWTO covers. Inplace of Javascript you use nothing but pure CSS (Cascading Style Sheets) and html, with the best part being that it should work on more or less any current browser.

First, what do I mean by "rollovers" well rather than drone on and on, have a look at this example of a typical horizontal navigation menu.


Menu 1 Menu 2 Menu 3 Menu 4 Menu 5

Move your mouse pointer over any of the menu entries and the background color should change to black, then back to blue once you move off the entry, thats what I mean by a rollover, now for how its done.

First thing to do is reduce the above example to its simplest component, a single link, with only the CSS needed to set the colors, and nothing else.

<html>
  <head>
    <style type='text/css'>
    <!--
        a.example       {       background-color:       #006699;
                                color           :       #ffffff;
                        }
        a.example:hover {       background-color:       #000000;
                        }
    -->
   </style>

  </head>
  <body>
  <a class='example' href='#'>Rollover test link</a>
  </body>
</html>

Before going through the above code, line by line, you will see that the CSS is actually embedded in the page header, and yes while this works its not the only way to use CSS to control the look of HTML, you can just as easily link to a external CSS file, which is just how I do things for this site. But for the purposes of this HOWTO, all styles are embedded.

The actual CSS is not that complex, and is broken up into two declarations, the first sets the default foreground and background colors for all links that are a member of the example class.

While the second sets the background color for all links that are part of this same class, but unlike the previous one does not set a default, as with the use of the "hover" pseudo class, the background color is only set when the mouse pointer hovers over the link in question.

Thats the end of the CSS, now a few words about the html, which as you can see is pretty normal with the exception of the "class" parameter. This is used to apply the class named by this parameter, and the styles it contains apply to the link in question, and only this link.

Related Pages and Links

  • Coming soon

Valid XHTML 1.0 Strict