Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 602
cadaa Avatar asked Oct 12 '10 09:10

cadaa


People also ask

How do you center a Li in UL?

Just give the list centered text (e.g. ul. nav { text-align: center; } ) and the list items inline-block (e.g. ul. nav li { display: inline-block; } ).

How do you center a floating element?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do you center a floated image in HTML?

To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div . Since the text-align property only applies to block-level elements, you place text-align: center; on the wrapping block-level element to achieve a horizontally centered <img> .


Video Answer


1 Answers

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

#container ul {
    display: inline-block;
}

#container li {
    float: left;
    height: 33px;
    line-height: 30px;
}
like image 117
reko_t Avatar answered Sep 19 '22 19:09

reko_t