开发者

Centering a ul with floated li

I have

<div id="container">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>

With the following CSS:

#container li {
float:left;
height:33px;
line-height:30px;
text-align:center;
width:auto;
}

#container{
 width:600px;
}

However I am having difficulty in horizontally centering th开发者_如何学编程e ul inside #container. It appears that I need a fixed width set on the ul for margin: 0 auto to work (needs text-align: center for IE). However I do not want to set a fixed width for the ul as the li items will be dynamic.

Please advise.


#container {
    width: 600px;
    text-align: center;
}

#container ul {
    display: inline-block;
}

#container li {
    float: left;
    height: 33px;
    line-height: 30px;
}


Here is a great solution: http://css-tricks.com/centering-list-items-horizontally-slightly-trickier-than-you-might-think/

<div id="menu-outer">
    <div class="table">
        <ul id="horizontal-list">
            <li><a href="#"><img src="images/list-item-1.gif" alt="list item 1" /></a></li>
            <li><a href="#"><img src="images/list-item-2.gif" alt="list item 2" /></a></li>
            <li><a href="#"><img src="images/list-item-3.gif" alt="list item 3" /></a></li>
            <li><a href="#"><img src="images/list-item-4.gif" alt="list item 4" /></a></li>
        </ul>
    </div>
</div>

Now see the very simple CSS that makes it happen:

#menu-outer {
    height: 84px;
    background: url(images/bar-bg.jpg) repeat-x;
}

.table {
    display: table;   /* Allow the centering to work */
    margin: 0 auto;
}

ul#horizontal-list {
    min-width: 696px;
    list-style: none;
    padding-top: 20px;
}
ul#horizontal-list li {
    display: inline;
}

It's the table div that get the job done. Some days I think "Whatever works." should be the slogan for CSS.


in css :

ul {
   float: left;
}

jquery

centerize = function(){
        var parentWidth = $("ul").parent("#container").width();
        var width = $("ul").width();
        var dif = (parentWidth - width) / 2;
        $("ul").css("margin-left", dif + "px");

    };

    centerize();

probably u need to work for every browser zoom, so add :

$(window).resize(function(){
    centerize();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜