Html 带显示的 div:内联块边距 0 自动不居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9313276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:35:23  来源:igfitidea点击:

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

htmlcss

提问by etlds

<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;

我尝试使用上面的代码来设置等于它的内容的宽度,然后将它的中心与 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>

回答by colosso

display:table; would position it in center too:

显示:表;也会将它放在中心位置:

CSS:

CSS:

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

HTML:

HTML:

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

Note: Using inline styles is a bad practice.

注意:使用内联样式是一种不好的做法。

回答by Rok Kralj

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

既然你要求 DIV 是inline-block,那text-align: center;就是答案。

<div style="text-align: center;">
<div style="display: inline-block; text-align: left;">
    <input id="abc" type="button" value="button" />
</div>
</div>

回答by Alan

Try

尝试

body {text-align: center;}