I often seen questions in forums asking how can you create horizontal menus in CSS without using tables.
This is actually quite straight forward and simply requires the use of UL within the HTML and a small amount of CSS (as opposed to all the table code required to achieve the same effect).
So the HTML for a simple menu then will be as follows:
<div id="menulist">
<ul>
<li><a href="item1.html">Item 1</a></li>
<li><a href="item2.html">Item 2</a></li>
<li><a href="item3.html">Item 3</a></li>
</ul>
</div>
Which will give a menu list that looks like the following:
- Item 1
- Item 2
- Item 2
So how do we turn it into a horizontal menu? This is where the CSS comes in!
In our CSS style sheet, we firstly we need to turn the bullets off, and set it to display inline, since by default UL is a block level element; thus:
#menulist ul {
list-style-type: none;
display: inline;
}
Now to get the menu items to display horizontally with a gap between each item:
#menulist ul li {
position: relative;
float: left;
margin-right: 20px;
}
And there we have it!
But what if you want the menu to be displayed on the right hand side of the page?
Well it’s as simple as changing the float: left to float: right. However, when you do this the menu items are reversed, i.e. Item 1 will appear on the right of the menu with Item 3 on the left. So you need to reverse the menu items in your list to counteract this.
This gives a menu list that is semantically correct without the need for tables.
Of course you can add background images, background color, borders, etc. to the list items to make them look as you desire, but the point is you don’t need to use tables to add any fancy graphics/style to the menu – it can all be done in CSS.
One last little trick to remember is to get the ANCHOR link to fill the whole width of the LI don’t specify any padding on the LI itself, put this on the ANCHOR and set the ANCHOR to be a block-element. This will mean hovering over the whole of the LI will activate the menu – rather than just the text.
#menulist ul li a { display: block; }
IE6 Issues
Now this all works fine in everything apart from IE6 or below, so we need to apply a fix for these old browsers, thus:
<!--[if lt IE 7]>
<style>
#menulist ul li a { display: inline-block; }
</style>
<![endif]-->
Be sure to place this code after your other styling, or any style sheets reference, otherwise it will get overridden!
So now we have it working consistently across all browsers.
Where this really wins overs tables is when you have sub-menus. With a table layout you would have to nest tables; and if you go to more than 2 levels of menu can become a real mess. For aural browsers this is a significant issue since the nested tables break up the correct semantic flow of the menu.
Whereas by using lists for your menu items the semantic flow is kept in tact, the code is neater, and if you need to amend it in the future (adding a new menu item for example) it’s a sinch!
