1. Computing

Discuss in my forum

Standards Based DHTML Menus

Menus that Appear When you Hover Over the Links

By

There are many ways to create DHTML menus, this tutorial will explain one way to do it using only CSS to create the drop-down menus. This tutorial takes advantage of the :hover pseudo-class and how CSS2 implements it across all elements to create a drop-down menu.

Here is how the menu will look and act.

First Create Your Top Level Headings in an Unordered List

The unordered list (UL element) is the perfect element to use for a menu, as that’s what a menu is—a list of navigation areas.

First create a list of your top level navigation elements, and give that UL the class of topmenu:

<ul class="topmenu">
<li><a href="">Home</a></li>
<li><a href="">Products</a></li>
<li><a href="">Contact Us</a></li>
</ul>

Then, in the LI element that will have the drop down menu, add the class submenu:

<li class="submenu"><a href="">Products</a></li>

Create the Sub-Menu

The sub-menu is just another unordered list that lives within the list item of the top level list. Place it after the text you want to appear in the main menu. Here is the list item with the sub-menu list:

<li class="submenu"><a href="">Products</a>
<ul>
<li><a href="">Product 1</a></li>
<li><a href="">Product 2</a></li>
<li><a href="">Product 3</a></li>
</ul>

</li>

Use CSS to Build the Menu Layout

Since this is a horizontal menu, with a vertical sub-menu, you need to style the lists so that they display correctly.

For both lists, you want them to be block elements, without margins, so add the following CSS:

ul.topmenu, ul.topmenu ul {
  display: block;
  margin: 0;
  padding: 0;
}

Then set the list items in the top menu to inline so they line up horizontally and give them a little padding on the right:

ul.topmenu li {
  display: inline;
  list-style: none;
  margin: 0;
  padding-right: 1.5em;
}

Write the CSS for the Sub-Menus

Of course, the sub-menu is still showing up on the page, so you should hide it:

ul.topmenu li ul {
  visibility: hidden; }

Then all you need is for the menu to appear when the user hovers over the enclosing list item:

ul.topmenu li.submenu:hover ul {
  visibility: visible;
}

Play with the positioning of the sub-menu to get it where you want it when it’s visible, and you’re done.

  1. About.com
  2. Computing
  3. Web Design / HTML
  4. About.com Web Design A to Z
  5. Books
  6. About Web Design Book
  7. AWD: Chapter 14
  8. DHTML Menus - Menus that Appear When you Hover Over the Links

©2014 About.com. All rights reserved.