A Simple Menu Using HTML Lists And CSS

The menu is a tried and trusted navigation tool used on thousands of websites. A typical example is used at the top of each page on this website. The menu shows the main links that people can click on to browse around. I’ve seen dozens of different ways to code a simple menu in HTML, usually involving a tangled mess of tables, divs, spans and any other markup the designer thought would be useful. If you think for a moment about what a menu actually is, you’ll see that it is just a list of links. The HTML that we use then should be just that, a list of links. Take the following for example:

<div id="menu">
    <ul>
        <li><a href="#">Who</a></li>
        <li><a href="#">What</a></li>
        <li><a href="#">Where</a></li>
    </ul>
</div>

This will give us something which looks like this:

It’s a good start but not particularly pleasing to the eye. What we need is some style, CSS style in fact. Adding the following styles makes a nicer looking menu:

#menu ul
{
    margin: 0px;
    padding: 0px;
    list-style-type: none;
}

#menu li
{
    list-style: none;
}

#menu a
{
    display: block;
    width: 8em;
    color: white;
    background-color: #000099;
    text-decoration: none;
    text-align: center;
}

#menu a:hover
{
    background-color: #6666AA;
}

By adding these styles to the list our menu now looks like:

You don’t have to stick with a vertical list either, by adding a little bit of style to the list items we can have a horizontal menu too.

If we add:

#menu li
{
    list-style: none;
    float: left;
    margin-right: 0.5em;
}

Our menu changes to look like:



Both of these types of menu use exactly the same HTML, the only difference is the CSS styles that are applied.
By separating the menu’s appearence from its markup it allows us to easily change how it looks. The HTML is also much cleaner than having lots of tables, divs and spans, it says what it is, a list of links.