Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center list items inside a UL element?

Tags:

html

css

How do I center list items inside a ul without using extra divs or elements. I have the following. I thought text-align:center would do the trick. I can't seem to figure it out.

<style>
ul {
    width:100%;
    background:red;
    height:20px;
    text-align:center;
}
li {
    display:block;
    float:left;
    background:blue;
    color:white;
    margin-right:10px;
}
</style>

<ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>

Check jsfiddle http://jsfiddle.net/3Ezx2/1/

like image 616
Pinkie Avatar asked Dec 27 '11 04:12

Pinkie


4 Answers

write display:inline-block instead of float:left.

li {
        display:inline-block;
        *display:inline; /*IE7*/
        *zoom:1; /*IE7*/
        background:blue;
        color:white;
        margin-right:10px;
}

http://jsfiddle.net/3Ezx2/3/

like image 61
sandeep Avatar answered Oct 24 '22 08:10

sandeep


A more modern way is to use flexbox:

ul{
  list-style-type:none;
  display:flex;
  justify-content: center;

}
ul li{
  display: list-item;
  background: black;
  padding: 5px 10px;
  color:white;
  margin: 0 3px;
}
div{
  background: wheat;
}
<div>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>  

</div>
like image 42
hamncheez Avatar answered Oct 24 '22 07:10

hamncheez


li{
    display:table;
    margin:0px auto 0px auto;
}

This should work.

like image 23
Kishore Kumar Avatar answered Oct 24 '22 09:10

Kishore Kumar


Looks like all you need is text-align: center; in ul

like image 15
Pencilcheck Avatar answered Oct 24 '22 08:10

Pencilcheck