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,810
  • 2
  • 23
  • 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

149

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,525
  • 3
  • 25
  • 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
  • 46,826
  • 10
  • 71
  • 80
  • 17
    `text-align: center;` will center inline *content* of the div, not the div itself. – yatskevich Feb 16 '12 at 14:51
  • Pardon, forgot to erase the CSS. Sorry. – Rok Kralj Feb 16 '12 at 14:52
  • No, that is not what I want. I want to center the div itself. – etlds Feb 16 '12 at 14:56
  • 2
    Note: this discussion is outdated. The answer has been since edited to include a wrapper div, such that the inner, original div is centered. So it is what he wants. – Kevin Wheeler Jul 11 '15 at 17:17
  • It adds an [annoying and] unwanted thin padding below my navbar anchor tags (when I hover over them they don't get the background color), but the accepted answer doesn't. (Although I don't like the accepted answer because it's hacky to me!) – aderchox Feb 15 '20 at 05:09
1

Try

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