开发者

Center horizontal list style menu

I have the following code:

CSS

#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;
}

HTML

<div id="main">
    <div id="links">
        <ul>
            <li>Link 1</li>
            <li>Link 2</li>
            <li>Link 3</li>
            <li>开发者_StackOverflowLink 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:

  • Centre widthless floats
  • Centering Float Left Menus


Add:

text-align:center;

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.


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:

CSS

#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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜