1

I am trying to center a ul and the li inside. I think the problem is the left margin of the last li. I tried two things but it does not seems to affect. What is the problem ?

CSS:

ul {
    position:relative;
    width: 640px;
    margin:40px auto;
    padding:0;
    list-style-type:none;
}

ul li {
    float:left;
    position:relative;
    width: 100px;
    padding: 0px;
    margin-right: 10px;
    background-color: #f2f2f2;
    display: block;
    height: 30px;
    line-height: 30px;
    text-align:center;
    font-family: verdana; 
    font-size:10px;
    color: #666
}

ul li:last-child { margin-right: 0px; }
/* ul li.last-item { margin-right: 0px; } */

HTML:

<ul>
  <li> first </li>
  <li> second </li>
  <li> third </li>
  <li> fourth </li>
  <li> fifth </li>
  <li> sixth </li>
</ul>

I have it here life: http://jsfiddle.net/a4aQN/

Nrc
  • 9,577
  • 17
  • 67
  • 114

1 Answers1

0

Here's the proper CSS to do that:

ul {
    margin: 40px auto;
    list-style-type:none;
    text-align: center;
}

ul li {
    width: 100px;
    padding: 0px;
    margin-right: 10px;
    background-color: #f2f2f2;
    display: inline-block;
    height: 30px;
    line-height: 30px;
    font-family: verdana;
    font-size:10px;
    color: #666
}

Updated jsFiddle

Essentially I put text-align: center; on your ul. You had some other things too that you didn't need, such as settings its width and the float: left; on your lis.

MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • This is really good! Thank you. In your case the last child is not needed? – Nrc Nov 04 '12 at 12:28
  • In the left side it appears a margin that makes it not totally centered. I dont' understand why?. It does not appear in Fiddle but it appears in a normal html and in JBin : http://jsbin.com/icomin/1/ and CodePen: http://codepen.io/anon/pen/jexAG – Nrc Nov 04 '12 at 12:35
  • 1
    I think your solution is really good but it needs to add the padding 0 in the ul and ul li:last-child { margin-right: 0px; } to be complitely centered: http://codepen.io/anon/pen/jexAG – Nrc Nov 04 '12 at 12:58