How to Use CSS to Position Horizontal Unordered Lists | WebReference

How to Use CSS to Position Horizontal Unordered Lists

How to Use CSS to Position Horizontal Unordered Lists

By Stu Nicholls.


Let's say that you've chosen to use a horizontal styled unordered list for your navigation and have followed the generally accepted CSS methods put forward by the many CSS information sites on the web. All's well until you decide that you don't want your menu to be left aligned. You want to be able to position it centrally or to the right and this is where it starts to get tricky.

Fortunately, there's a way to style your horizontal unordered list so that it can be easily positioned where you want it.


The accepted 'normal' method of styling

In this tutorial I'll use the following unordered list throughout.


<ul id="menu">
<li><a href="#nogo">Item one</a></li>
<li><a href="#nogo">Item two</a></li>
<li><a href="#nogo">Item three</a></li>
<li><a href="#nogo">Item four</a></li>
<li><a href="#nogo">Item five</a></li>

..which looks like this before styling.

The normally accepted method of styling this list is as follows.


font-family: arial, helvetica, sans-serif;
#menu li {display:inline;}
#menu li a
padding:0.2em 1em;
border:1px solid #000;
#menu li a:hover

#menu - the <ul> tag styling

#menu li- the <li> tag styling

#menu li a- the <a> tag styling

#menu li a:hover- the <a> tag hover styling

Using the above styling our unordered list will look like this:

‡ Normal Styling

It all looks ok but as soon as you try to reposition the menu your troubles begin.

If, for instance, we want to center our menu we could try changing the margins of the <ul> tag to margin:0 auto; but this doesn't work. We could try using text-align:center; but this also doesn't work.

To understand why these methods don't work, let's take a closer look at the styled list and ask ourselves: "What is the overall size of the <ul>?" If you guessed that it's the same size as the outer black border you would be wrong.

To show the actual size of the <ul> let's add a red border around it.

Created: March 27, 2003
Revised: August 26, 2005