当我设置display:block;和宽度:auto;在按钮上,我希望按钮可以拉伸以填充容器,就像其他块元素一样.出于某种原因,它没有,至少在最新的Chrome中没有.
当谷歌搜索时,我发现很多人都在问同样的问题,他们对“我如何拉伸按钮来填充容器”的答案感到满意?这不是我感兴趣的.(我完全能够以任何方式拉伸我的按钮.)检查按钮属性,包括浏览器默认强加的按钮属性也没有帮助我.
我想了解,是什么导致按钮忽略显示:块;宽度:自动;并根据其内容保持水平尺寸.
这是我的意思:
button { display: block; }
<button style="width: auto;">button with `display:block; width:auto;`</button> <button style="width: 100%;">button with `display:block; width:100%`</button>
我希望按钮的宽度为:auto;也被拉长了.
为了绝对清楚,这不是input with display:block is not a block, why not?或任何类似问题的重复,除非只有答案描述了拉伸相关元素的方法.
编辑:它可能是What is it in the CSS/DOM that prevents an input box with display: block from expanding to the size of its container的副本.另一方面,该问题根本没有提到按钮.你需要阅读答案,找出它也适用于按钮.
(这个 source and possible dublicate的答案的无耻副本,从 this article中提取了信息.)There are a few elements (
<input>
,<select>
,<button>
,<img>
,
<object>
, and<textarea>
) that are considered replaced elements
whose appearance and dimensions are defined by an external resource.
(e.g. the operating system, a plugin, etc).Replaced elements can have intrinsic dimensions—width and height
values that are defined by the element itself, rather than by its
surroundings in the document. For example, if an image element has a
width set to auto, the width of the linked image file will be used.
Intrinsic dimensions also define an intrinsic ratio that’s used to
determine the computed dimensions of the element should only one
dimension be specified. For example, if only the width is specified
for an image element—at, say, 100px—and the actual image is 200 pixels
wide and 100 pixels high, the height of the element will be scaled by
the same amount, to 50px.Replaced elements can also have visual formatting requirements imposed
by the element, outside of the control of CSS; for example, the user
interface controls rendered for form elements.使用HTML5,您可以使用其他更多类似的< audio>和< canvas>和some more.
请注意 – 正如您将在评论中的讨论中看到的那样 – 按钮实际上并不是replaced element defined by w3c.但是它表现得像一个,这将在this article进一步讨论.