0

I have a horizontal unordered list I want to center horizontally in a div container (that's arbitrarily bigger than the list). I was thinking of displaying the ul as a block and using auto margins to center the list within its parent container. But... I can't seem to get the ul to display as a block and not take 100% width.

From what I understand, block elements take the required width to wrap around children elements (unless they're uncleared floats or absolute positionned), so I would think that placing the ul and li's as blocks should do the trick. Unfortunately it doesn't and I don't understand why.

Any idea?

Here's the code: http://jsfiddle.net/kccbg/1/

Prusprus
  • 7,987
  • 9
  • 42
  • 57

3 Answers3

2

Try using display: inline-block instead, and setting text-align: center for the container like so:

HTML:

<div class="container">
    <ul>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
    </ul>
</div>​

CSS:

.container{
    width:100%;
    background-color:#CCC;
    height:20px;
    text-align: center;
}
ul{
    display:inline-block;
    margin:0 auto;
}
li{
    display:inline-block;
}

Example

Zhihao
  • 14,758
  • 2
  • 26
  • 36
  • 1
    You can further improve this by removing the unnecessary floating and clearfix applied to the li's – user110857 Jun 19 '12 at 19:40
  • @gmeben, you're right, thanks. I was just building off of what the OP initially had. I've edited my answer with your suggestions. – Zhihao Jun 19 '12 at 19:44
  • Are inline-blocks a better solution than floats from a compatibility standpoint? Especially with IE7 and below i assume? – Prusprus Jun 19 '12 at 19:48
  • I don't think inline-blocks play very nicely with IE7 and lower. You might want to take a look at [this post](http://stackoverflow.com/questions/5838454/inline-block-doesnt-work-in-internet-explorer-7-6), and see if you can get the right look you want. – Zhihao Jun 19 '12 at 20:10
  • Yes usually specifying zoom:1 on an inline-block remedies the problem in IE7 – Prusprus Jun 20 '12 at 13:04
2

UPDATE: (based on comment from gmeben)

Change the css to:

.container{width:100%; background-color:#CCC; text-align:center}
li{display:inline;}

and remove

<li class="clear"></li>

from html.

No floats and clearing and no inline-block (not supported/rendered-correctly by all browsers).

  • The ul doesn't need to be declared as a block-level element and the `.container` doesn't need a height property associated with it. – user110857 Jun 19 '12 at 19:44
0

If you know the total width of your list items, you can set the width of the <ul> and then set its margin to 0 auto. jsFiddle example.

CSS

.container{
    width:100%; 
    background-color:#CCC; 
    height:20px;
}
ul{
    list-style:none;
    width:200px;
    margin:0 auto;
}
li{
    float:left; 
}

j08691
  • 204,283
  • 31
  • 260
  • 272