With the fo...">

Centering a ul with a floating line

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 horizontal centering ul inside the #container . It looks like I need a fixed width set to ul for margin: 0 auto to work (requires text-align: center for IE). However, I do not want to set a fixed width for ul, since li elements will be dynamic.

Please inform.

+7
html css html-lists
source share
3 answers
 #container { width: 600px; text-align: center; } #container ul { display: inline-block; } #container li { float: left; height: 33px; line-height: 30px; } 
+14
source share

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 let's look at simple CSS that does this:

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

This is a div table that does its job. Some days I think, β€œWhatever happens.” should be a slogan for CSS.

+4
source share

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(); 

you may need to work for every browser increase, so add:

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

All Articles