<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>
`margin:auto;` doesn't work on inline-block elements.
First things first, each of the elements above are blocks and have set margin: 0 auto, but it does not work since blocks have width equal to 100% by default (the first example). The block covers the whole page and therefore cannot be centered.
After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property. Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With