Tutorial :Center horizontal list style menu


I have the following code:


#main  {      width:100%;      height:120px;      border:solid 1px #efefef;  }    #links  {      background-color:#808080;  }    #links ul  {      margin:0px auto;      padding:0px;      list-style:none;      background-color:#eee;      height:30px;  }    #links ul li  {      float:left;      margin:0px;      list-style:none;      padding:0px 10px;  }  


<div id="main">      <div id="links">          <ul>              <li>Link 1</li>              <li>Link 2</li>              <li>Link 3</li>              <li>Link 4</li>              <li>Link 5</li>              <li>Link 6</li>          </ul>          </div>  </div>  

The list items are dynamic so I can't really use fixed width on the #links layer and I want the list to be perfectly centered. The above code doesn't work and I've a variety of methods but can't seem to get the list centered.

I don't want to use a table partly because I hate using tables for menus and also I will have eventually have sub menu items that will also be horizontal.

Any pointers?

Thanks Steve


Here are the possible solutions:




To #links

#links ul sets the left and right margins to auto. Which will make them equal size if the container is told to center its contents. The line above will do that.


Here's something I wrote that may do what you want. Uses jQuery though. Evenly spaced and justified horizontal list menu


A little style detail to Safraz answer (thank you that worked for me too!)

When I set left:%50 of the ul, and left:-50% of the li items. The browser shows a horizontal scrolling bar, though there's nothing to see (the scrollbar is there because of the overflow that is produced by the UL with left 50%), so the solution is to add to the wrapping div (in this case id=links) this style:


#links  {      /* .... */      overflow-x: hidden ;  }  


Margin 0 auto only works when you give a width! you need to use inline block, then text align center

ul {      text-align: center;          }  ul > li {      display: inline-block;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »