How to distribute HTML list items evenly in an unordered list

at. picture at. · Nov 12, 2012 · Viewed 49.6k times · Source

I want my li elements that form a horizontal menu to be distributed evenly across the width of my ul element. I normally float my li elements to the left and add some margin. But how do I put the proper spacing so they extend from the left of my ul element to the right edge?

Here's an example jsfiddle of a menu not distributed across the ul.

The spacing has to be the same between each li. But the li elements may be different lengths.

Answer

FireCrakcer37 picture FireCrakcer37 · Nov 14, 2012

Yet another approach. This is something I use when trying to span a menu evenly across the page. It is nice if you have a dynamic menu that will change depending on certain conditions (like an admin page that only shows up if you are logged in as an admin).

CSS:

nav div ul {
display: table;
width: 100%;
list-style: none;
}
nav div ul li {
display: table-cell;
text-align: center;
}
nav div ul li a {
display: block;
}

I was kinda lazy, and just copied this from my current project, so you will have to adapt it to fit your code, but it is my preferred method of creating a horizontal menu

EDIT: You can make it look like it spans better by adding this:

CSS:

nav div ul li:first-child {
    text-align: left;
}
nav div ul li:last-child {
    text-align: right;
}

again, untested, just typed.