72
<div style="display: inline-block; margin: 0 auto;">
    <input id="abc" type="button" value="button" />
</div>

I try to use the code above to set the width of equal it's content, and then center it with margin: 0 auto;

But it did not work for me on any browser. Any suggestion?

BTW, when I set the width property, it works fine.

<div style="width: 10em; margin: 0 auto;">
    <input id="abc" type="button" value="button" />
</div>
etlds
  • 5,598
  • 2
  • 20
  • 30
  • Per @Xander comment, without a width, a DIV will expand to 100% of it's container. So "margin:0 auto" isn't likely going to show any effect as you'll need something smaller than 100% width. If you're just trying to center the button, why not just center align text? ie. "text-align:center" in the DIV style. I think INPUT tags are inline naturally, so it should center itself inside the DIV> – jmbertucci Feb 16 '12 at 14:50
  • 1
    @Fozzyuw, no matter the width is necessary or not, when we set display: inline-block, the width will be set equal to its content. – etlds Feb 16 '12 at 14:58
  • Your second example works, because you removed the `display: inline-block`. When you add it back again, setting the width has no effect. See http://jsfiddle.net/anEvF/ – Olaf Dietsche Oct 01 '13 at 15:23
  • 1
    If you stumble upon this thread but none of the answers work for you, check that your div is not floated. `margin: auto` does not play nicely with `float`. – skibulk Jun 07 '16 at 18:32

3 Answers3

148

display:table; would position it in center too:

CSS:

  .button{
    display: table;
    margin: 0 auto;
    }

HTML:

<div class="button">
<input id="abc" type="button" value="button" />
< /div>

Note: Using inline styles is a bad practice.

colosso
  • 2,495
  • 3
  • 24
  • 49
53

Since you requested DIV to be inline-block, text-align: center; is the answer.

<div style="text-align: center;">
<div style="display: inline-block; text-align: left;">
    <input id="abc" type="button" value="button" />
</div>
</div>
Rok Kralj
  • 43,948
  • 10
  • 67
  • 80
1

Try

body {text-align: center;}
Alan
  • 33
  • 1