【问题标题】:button is an inline element but width is working?按钮是内联元素但宽度有效?
【发布时间】:2015-01-04 09:23:34
【问题描述】:

Button是一个内联元素,但是宽度属性起作用就可以了,怎么会?

button {
    width: 300px;
}
<button>asdfsdf</button>
<button>234234d</button>

【问题讨论】:

    标签: html css inline


    【解决方案1】:

    根据(非规范)Appendix D. Default style sheet for HTML 4,大多数浏览器默认将button 元素显示为inline-block

    因此,您可以期望 width 属性能够正常工作,如 Calculating widths and margins - Inline-block, non-replaced 中所述。

    但不仅如此。 button 元素为replaced elements

    在 CSS 中,被替换元素是一个表示为 超出了 CSS 的范围。这些是一种外部对象,其 表示独立于 CSS。

    因此,它们有一些特殊的行为。例如,根据Calculating widths and margins - Inline, replaced,无论它们是否具有display: inline-blockdisplay: inline,它们的大小都遵循width 属性。

    值得注意的是,HTML5 无论如何都会强制它们显示为inline-block。这在10.5.2 Bindings - The button element中有解释:

    @namespace url(http://www.w3.org/1999/xhtml);
    button { binding: button; }
    

    button 绑定应用于 button 元素时,该元素 预计将呈现为呈现为按钮的“内联块”框 其内容是元素的内容。

    【讨论】:

    • 这个答案应该是任何按钮相关问题的最佳答案。
    【解决方案2】:

    参见W3C Reference(HTML4 元素默认 CSS 样式列表)

    button 是一个inline-block 元素(默认情况下),可以设置width,而不是inline 元素

    【讨论】:

    • display: inline 将被忽略,但 display: block 不会被忽略 - 很奇怪 :)
    【解决方案3】:

    为什么不设置min-width: 300px;

    即使按钮是inline-block,它也对我有用。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多