按钮是一个内联元素,但它的宽度属性有效。这是为什么?
button {
width: 300px;
}
<button>asdfsdf</button>
<button>234234d</button>
最佳答案
根据(非规范的)Appendix D. Default style sheet for HTML 4,大多数浏览器默认将 button
元素显示为 inline-block
。
因此,您可以期望 width
属性起作用,如 Calculating widths and margins - Inline-block, non-replaced 中所述。
但不仅如此。 button
元素是 replaced elements :
In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS.
因此,它们有一些特殊的行为。例如,无论它们是否具有 display: inline-block
或 display: inline
,它们的大小都根据 width
属性确定,根据 Calculating widths and margins - Inline, replaced .
值得注意的是,HTML5 强制将它们显示为 inline-block
。这在 10.5.2 Bindings - The button
element 中有解释:
@namespace url(http://www.w3.org/1999/xhtml); button { binding: button; }
When the button binding applies to a
button
element, the element is expected to render as an 'inline-block' box rendered as a button whose contents are the contents of the element.
关于html - 按钮是一个内联元素,但宽度有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764122/