div with display:inline-block margin 0 auto not center
Asked Answered
M

3

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>
Michelinamicheline answered 16/2, 2012 at 14:44 Comment(4)
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>Peebles
@Fozzyuw, no matter the width is necessary or not, when we set display: inline-block, the width will be set equal to its content.Michelinamicheline
Your second example works, because you removed the display: inline-block. When you add it back again, setting the width has no effect. See jsfiddle.net/anEvFMoil
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.Metamorphose
I
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.

Iorio answered 16/2, 2012 at 14:55 Comment(1)
@kapa I know this is an old comment, but I would probably consider that a positive. :)Valona
F
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>
Fylfot answered 16/2, 2012 at 14:48 Comment(5)
text-align: center; will center inline content of the div, not the div itself.Aksoyn
Pardon, forgot to erase the CSS. Sorry.Fylfot
No, that is not what I want. I want to center the div itself.Michelinamicheline
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.Economy
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!)Llama
P
2

Try

body {text-align: center;}
Pharmacist answered 20/5, 2015 at 23:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.