Horizontal menus and list items with definite widths

Published on October 16th 2009.

Modified on July 2nd 2010.

This tutorial explains how to create a horizontal menu with list items of a definite width. In other words, a menu where you are able to set the width of the list-items, in contrast to a menu where the list-items have automatic widths (if that's what you want to do, check out the tutorial on Horizontal menus and list items with automatic widths).

A basic menu with list items all the same width

Your main reason for wanting to give your list-items definite widths will probably be because you want them all to be the same size; not different lengths depending on their content. Let's demonstrate how that's done.

Example

Here, we'll create a basic horizontal menu with list-items of a width of 100px.

CSS Code:

        
			#horizMenu {
				margin:0;
				padding:0;
			}
			#horizMenu li {
				display:block;
				width:100px;
				float:left;
				margin-right:6px;
			}
        

(X)HTML Code:

			<ul id="horizMenu>
			<li>Up</li>
			<li>Down</li>
			<li>Charm</li>
			<li>Strange</li>
			<li>Top</li>
			<li>Bottom</li>
			</ul>
        

Result:

Here is our finished product. As you can see, our menu items all have the same width, which adds a certain uniformity, don't you think?

The six flavours of elementary particles known as quarks.

Explanation

The display:block on the list items converts them to block elements, which means we are able to manipulate their widths. We give them a width of 100px, which, for this menu, is sufficient, and will not cause any of our text to spill over onto the next line if the user increases the text size. Next, we apply a float:left to our lis, to get them to float next to each other.

There's another piece of CSS I've added that is very important: overflow:auto. Because our list-items have been given a float:left and our menu doesn't have a definite height, this causes the float to "leak" out of the menu, i.e., the menu to behave as if it doesn't have content. We rectify this by adding overlofw:auto to the menu (or giving it a definite height), which gently reminds it that it does have content. overfow:auto in effect stretches our menu down to cover its items, so all the other objects on the page know they are there.

For more on expanding elements to fit their contents, see my tutorial on The top 10 things you've always wanted to do in CSS.

Got any questions or comments? Feel free to mail me @ helen@alternategateways.com.

Share this:

Back to resources.