Centering a ul with floated li
Asked Answered
B

3

7

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 the 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.

Batt answered 12/10, 2010 at 9:38 Comment(0)
C
14
#container {
    width: 600px;
    text-align: center;
}

#container ul {
    display: inline-block;
}

#container li {
    float: left;
    height: 33px;
    line-height: 30px;
}
Corves answered 12/10, 2010 at 9:41 Comment(2)
Thank you but doesn't inline-block not work in IE6 (and IE7?)?Batt
You can try this trick to make it work with IE (I can't verify whether it works, as I'm on a Mac right now). Add this to #container ul: zoom: 1; *display: inline; The rationale behind this is explained here: blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-blockCorves
C
4

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.

Caliph answered 1/9, 2012 at 7:54 Comment(0)
S
0

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();
});
Starla answered 17/6, 2013 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.