Dropdown menus and menu bars have been heavily used since the early days of graphical user interfaces. Their use has become ubiquitous, and even expected, in desktop applications, and the web has quickly followed suit. This article is intended to describe an extremely basic, yet extremely powerful, technique for adding dropdown menus in your application user interface or website design.

Getting Started

To begin, we need to define our basic menu hierarchy. In order to maintain a structured and semantic approach to this, we will use nothing more than unordered lists of standard links. We’ll use the following code as an example:

Creating Dropdown Lists

With our semantic HTML and link structure written out, we can proceed to apply some basic hover techniques that are included in CSS. The :hover pseudo-class is invoked when the mouse is placed over the list item.

We can use CSS to hide the child unordered lists by default, and show them with the :hover pseudo-class, like so:

The Issue with Internet Explorer

Unfortunately, while the :hover pseudo-class may be elegant, it does not work in Internet Explorer. At this point, a short bit of JavaScript is required to provide a clean fix. All we need to do is select all unordered lists that are within a list item that has the class .headlink and add onmouseover and onmouseout events to them. This can be done in twelve simple lines of code:

Putting It All Together

The dropdown menu is now functional in the major browsers, and is ready to be styled, cleaned up, and shipped.

It is advantageous to start by applying a basic style that’s a little more appealing than the standard lists. This allows us to visualize how this will fit into our application or design.

Adding Some Flare

With a few extra lines of CSS, the menu is styled and ready to fit into our site.

Wrapping Up

One important aspect of writing a generic dropdown list is to segregate the CSS and JavaScript to ensure that there are no conflicts. The easiest way to do this is to add the #cssdropdown selector in front of every element.

Finally, we check to see if the #cssdropdown div can be moved around freely. This ensures that dropdown menu we have created will flow nicely when integrated with our existing site design or application user interface.