Hey all. I am trying to get my navigation menu items to center into the middle of my navigation. This is my markup and CSS:

<div id="nav">
        <li><a href="#">Search</a></li>
        <li><a href="#">Memberlist</a></li>
        <li><a href="#">Ticker</a></li>
        <li><a href="#">Register</a></li>
        <li><a href="#">Login</a></li>

The CSS:

#nav {
    background: url('images/nav.gif') no-repeat;
    width: 960px;
    height: 35px;

#nav ul {
    list-style-type: none;

#nav ul li {
    display: inline;
    line-height: 31px;

#nav li a {
    display: block;
    float: left;
    height: 35px;
    text-decoration: none;
    margin: 0px 5px 0px 5px;
    color: #FFF;
    font-weight: bold;
    font-size: 0.8em;

Problem is, it's currently aligned to the left (predumably because of the float: left; on the a elements) and I need it in the center. I have tried surrounding it in a DIV and using margin: 0 auto; and also applying that to the ul element but it doesn't work.

Does anyone have a solution? Thanks :)

2 answers

This was chosen as the best answer

See Stu Nicholas' page. It uses the position:relative, left:50% and right:50% technique. By the way, this has been asked quite a number of times at StackOverflow.

Answered almost 9 years ago by Ahmad Syukri

something like this:

#nav ul {
        list-style-type: none;
            margin: 0 auto;
            width: 30%;

should get you started.

for an element to be centered with margin: 0 auto; it has to be narrower than its parent. Set an appropriate width and you're sorted. (block level elements without a declared width assume 100% width)

Answered almost 9 years ago by Tony Crockford
  • That does work but it doesn't allign all the menu items directly in the center. I can change how close to the center it's aligned by changing the width but it still seems hacky. The menu will be dynamic aswell so this isn't really a solution. But thanks :) Kratz almost 9 years ago
  • removing padding from the ul with padding:0; will make it more consistent, but you have to set a width... javascript? Tony Crockford almost 9 years ago