Using lists for menus

One thing, almost every site has, is a menu. How else do you expect your visitors to reach all the content on you site? But how do you create a nice, content-from-layout-separated menu? You use lists, preforably unnumbered lists. Let me show you how…

There are two cases that can occur: or you have only a root menu (just items) or your root menu also contains children (subitems).
The first case is the easiest, you create something like this:

<ul id="menu">
  <li><a href="page1.html">Item 1</a></li>
  <li><a href="page2.html">Item 2</a></li>
  <li><a href="page3.html">Item 3</a></li>
  <li><a href="page4.html">Item 4</a></li>
</ul>

Easy as that. Now you can start applying style to it.
First let’s get rid of those bullits:

#menu {
  margin: 0;
  padding: 0;
  list-style-type: none;
  width: 15em;
}

As you can see, I also gave the menu an id, so this style only applies to the menu and I can still have unnumbered lists with bullits in the rest of the document, and I also removed the extra spacing in front of the items. Further, the menu is 15em wide, which is a little more than 15 characters (since M is one of the widest characters, all others are smaller) or about 250px for those who like to work in pixels.

That will take care of the menu’s structure. You can now go crazy on the coloring of it. Just define the li element in your css to define an item and ul for the whole list.

Now how about subitems?
A subitem is nothing more than a menu inside a menu, like this:

<ul id="menu">
  <li><a href="page1.html">Item 1</a>
    <ul class="submenu">
      <li><a href="subpage1.html">SubItem 1</a>
      <li><a href="subpage2.html">SubItem 2</a>
      <li><a href="subpage3.html">SubItem 3</a>
    </ul>
  </li>
  <li><a href="page2.html">Item 2</a></li>
  <li><a href="page3.html">Item 3</a></li>
  <li><a href="page4.html">Item 4</a></li>
</ul>

Now you only need to define the style for the submenu exactly like you did with the root menu. In this case, the submenu are assigned a class submenu, just to make it easier to define style to only the subitems. This style may look something like this:

#menu ul.submenu {
  margin: 0;
  padding-left: 2em;
  list-style-type: none;
}

This way all the subitems will be indented by 2em. You can create menus with unlimited submenus (not likely you will do this, but it is possible). And they are valid, accessible and style is separated from structure (unlike the <br /> option).

No Responses to “Using lists for menus”.

Comments are closed.