<input /> with display:block in text-align:center div

时间:2011-01-15 08:38:17

标签: html css

有了这个:

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

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

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

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

按钮与IE7中心对齐 - 在FF,Chrome和IE8中未与中心对齐

为什么呢?并且具有display:block的按钮(或任何&lt; input&gt;)可以以某种方式居中对齐吗? (除了使用&lt; center&gt; - 适用于所有提到的浏览器,顺便说一句 - 但是“被禁止”......)

3 个答案:

答案 0 :(得分:10)

这样可以起作用:

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

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

答案 1 :(得分:1)

来自css standard

  

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

所以当你的元素(无论它们是什么,div,spans,input等)都是内联的时,text-align会对它们产生影响,当它们显示时:block,按标准定义,text-align将不对齐

你可以通过设置margin:0 auto和固定宽度来修复这个问题,比如steweb建议的,或者(根据你的具体要求):

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

答案 2 :(得分:0)

显示为blocks are centred with auto margins的元素。 text-align媒体资源应仅以inline children为中心。 Internet Explorer存在漏洞。