Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

<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> 
like image 544
etlds Avatar asked Feb 16 '12 14:02

etlds


People also ask

Does margin auto work on inline block?

`margin:auto;` doesn't work on inline-block elements.

Why margin 0 Auto does not work?

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.

How do I center a div with a display block?

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.


2 Answers

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.

like image 152
colosso Avatar answered Sep 20 '22 23:09

colosso


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> 
like image 34
Rok Kralj Avatar answered Sep 16 '22 23:09

Rok Kralj