tags:

views:

168

answers:

3

I know this question had been asked many times.

http://stackoverflow.com/questions/1740587/float-a-div-to-center

However, I follow their suggestion :

<center>
  <div style="margin : auto; text-align: center">
    <a href="#" style="float: left; margin-right: 10px;">Menu Item 1</a>
    <a href="#" style="float: left; margin-right: 10px;">Menu Item 2</a>
    <a href="#" style="float: left; margin-right: 10px;">Menu Item 3</a>
  </div>
</center>

alt text

By using "Center" and "Margin Auto", "Text Align Center" ... I still unable to center the menu item.

+2  A: 

Your code works fine, but the div is 100% wide by default so you won't notice any centering.

Either give the div a width (fixed in pixels or relative in percent) or, if you just want to center the menu items, give the div a text-align setting:

<div style="margin : auto; text-align: center">
Pekka
It doesn't work either. See my update.
Yan Cheng CHEOK
@Yan remove the `float: left` from your links and it will work.
Pekka
I need to use float left too.
Yan Cheng CHEOK
@Yan Elements with a `float: left` can't be centered. You could only center the `div` then by giving it a width.
Pekka
A: 

Why not use an unordered list? After all, you are creating a list of links.

<ul>
 <li><a href="#">Menu Item 1</a></li>
 <li><a href="#">Menu Item 2</a></li>
 <li><a href="#">Menu Item 3</a></li>
</ul>

li {
  display: inline;
}

ul {
  width: 50%;
  margin: 0 auto;
}
Chris
Not his question but good point.
Pekka
I need to use div. The example I gave is just a simplified version.
Yan Cheng CHEOK
A: 

use inline-block instead of float left.

<center>
  <div style="margin : auto; text-align: center">
    <a href="#" style="display: -moz-inline-box; display: inline-block; left; margin-right: 10px;">Menu Item 1</a>
    <a href="#" style="display: -moz-inline-box; display: inline-block; margin-right: 10px;">Menu Item 2</a>
    <a href="#" style="display: -moz-inline-box; display: inline-block; margin-right: 10px;">Menu Item 3</a>
  </div>
</center>
Yan Cheng CHEOK