Html <input> with display:block 在 text-align:center div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4698696/
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-29 06:10:36  来源:igfitidea点击:

<input> with display:block inside a text-align:center div

htmlcss

提问by Yuval A.

With this:

有了这个:

<div id="parentdiv" style="text-align:center;width:600px;margin:auto;">
  <input type="button" value="push me" />
</div>

The button is aligned to the center of the browser window (as desired) in FF, Chrome, IE7 and IE8.

在 FF、Chrome、IE7 和 IE8 中,该按钮与浏览器窗口的中心对齐(根据需要)。

But, add "display:block" to the button:

但是,在按钮上添加“display:block”:

<div id="parentdiv" style="text-align:center;width:600px;margin:auto;">
  <input type="button" style="display:block;" value="push me" />
</div>

The button is aligned to the center in IE7 - and is not aligned to the centerin FF, Chrome and IE8.

该按钮在 IE7 中与中心对齐 - 而在 FF、Chrome 和 IE8 中未与中心对齐

Why? And can a button (or any <input>) with display:block be center-aligned in some way? (other than using <center> - which works on all browsers mentioned, btw - but is "forbidden"...)

为什么?带有 display:block 的按钮(或任何 <input>)能否以某种方式居中对齐?(除了使用 <center> - 它适用于所有提到的浏览器,顺便说一句 - 但被“禁止”......)

回答by stecb

This way it can work:

这样它就可以工作:

<input type="button" style="width:100px;margin:0 auto;display:block;" value="push me" />

To force a block input (originally display:inline element) to be centered, you have to set a fixed width and then the margin to 0 auto ;)

要强制块输入(最初显示:内联元素)居中,您必须设置固定宽度,然后将边距设置为 0 auto ;)

回答by davin

from the css standard:

css 标准

This property describes how inline contents of a block are horizontally aligned

此属性描述块的内联内容如何水平对齐

so when your elements (no matter what they are, divs, spans, inputs, etc.) are inline, text-align has an affect on them, and when theyre display:block, by standard definition, text-align will not align them

因此,当您的元素(无论它们是什么,div,跨度,输入等)是内联的时,文本对齐会对它们产生影响,并且当它们显示:块时,根据标准定义,文本对齐不会对齐它们

you can fix this by setting margin:0 auto and fixing a width, like steweb suggested, or alternatively (depending on your specific requirements):

您可以通过设置 margin:0 auto 并固定宽度来解决这个问题,就像steebeb建议的那样,或者(取决于您的具体要求):

<input type="button" style="display:inline-block;" value="push me" />

回答by Quentin

Elements that are displayed as blocks are centred with auto margins. The text-alignproperty should only centre inline children. Internet Explorer has bugs surrounding this.

显示为块的元素以自动边距居中。该text-align属性应仅居中内联儿童。Internet Explorer 有围绕这一点的错误。