Using lists for menus
A menu is a list of the main pages on a website so why shouldn’t you use html lists for building them? Two common reasons for not doing so are
- I don’t want those dots in front of the links
- There is so much whitespace that they are useless for menus
But those problems disappear as soon as you apply a little CSS to them.
Let’s just mention some reasons to use lists
- Html list tags are short
- A menu is a list
- Other types of user agents (text browsers, cellphones etc.) will better understand how to represent your menu because list tags carry meaning, divs and tables does not.
Ok, now it’s time to start with the html for a simple menu. We will use an unordered list (specified with <ul>) because you don’t have to read the pages in the specified order.
<ul id="menu">
<li>Widgets</li>
<li>Gadgets</li>
<li>Subjects</li>
</ul>
To avoid the problems mentioned above we have to apply a little css to our menu. To remove the list markers (dots) we will apply list-style-type: none; to the ul. To avoid excessive whitespace we must specify margin and padding on both the list and all the list items within it. A border is not really necessary but I want one to make the menu more visible on this page.
#menu{
list-style-type: none;
padding: 0px;
margin: 10px;
width: 120px;
border: 1px solid #FF5C00;
}
#menu li{
padding: 0px;
margin: 3px 5px;
}
That is a margin of 3px above and below each list item and 5px to the left and right:
- Widgets
- Gadgets
- Subjects
Now, that looks more like a menu! (If it had links)
But if I want a horizontal menu? Just one and a half change. List items are normally rendered as block level elements which implies that each list item should be placed below the previous but this can be changed with display:inline; in the CSS code for the list items. If you are unfamiliar with the different display types available you should read about the CSS display property at W3schools
The width of the whole list must also be changed to make room for the horizontal orientation.
#menu{
list-style-type: none;
padding: 0px;
margin: 10px;
width: 300px;
border: 1px solid #FF5C00;
}
#menu li{
display: inline;
padding: 0px;
margin: 3px 5px;
}
And the result :
- Widgets
- Gadgets
- Subjects
Just one note for those who need fine control over the spacing of the menu items; Some browsers apply extra whitespace between these list items if there is whitespace between the </li> and <li> tags
That’s the basics of using lists for menus. As you see, the html code is very, very short and you are encouraged to use CSS for creating the visual appearance. The menu might look boring now, so head over to the Listamatic and fix that.