Creating dropdown menus

Although dropdown menus are a bit more complicated than vertical or horizontal menus, they do use many of the same techniques. In fact, dropdown menus often combine the two techniques by having a top-level horizontal menu that features vertical dropdown menus.

To create dropdown menus, you start with a series of nested lists. Each nested list represents a dropdown menu, and should be nested inside the list item it represents. You can create multi-level dropdowns by having consecutive nested lists. Most people identify top-level and submenus by applying class attributes to the lists that identifies the menu type. The support of more advanced CSS selectors makes this unnecessary, but adding the classes helps the overall semantics of your menus and can make authoring the styles easier.

There are two real tricks to creating CSS-driven submenus. First is to hide the submenus when they’re not needed, and then show them when a user hovers over the relevant link. To accomplish this you could set the initial display property of the submenu to none, set the initial visibility to hidden, or reposition the submenu off the page. When the appropriate link is hovered over, you simply set the display property back to block, visibility to visible, or change the positioning back to the desired location. You could even use the opacity property in a similar fashion. Of those techniques, I prefer to position the submenus, as modifying the display often results in screen readers ignoring the submenus. The second major concern is how to display an “active” state on the top-level link as you browse the submenus. This is accomplished by writing a selector that activates the submenus based on the user hovering over the parent list item of the submenu. We’re tempted to try to trigger the submenu on the relevant parent link, but that would not allow us to browse the submenu once the user has moved away from the parent link.

Dropdown menu example