根据 MDN , button
是一个内联元素。
但是,按钮元素有default styling使用 display: inline-block
(参见 this question)
button, textarea,
input, select { display: inline-block }
到目前为止一切顺利。
但是:
如果我现在使用 display:inline
设置按钮 - 宽度仍然适用!!
DEMO
button,
div {
width: 200px;
border: 1px solid red;
display: inline;
}
<button>button</button>
<div>div</div>
现在,根据spec : width
不适用于内联元素(不可替换)
Applies to: all elements but non-replaced inline elements, table rows, and row groups
既然如此:
为什么宽度仍然适用于内联 button
元素?
最佳答案
正如评论中所提到的,我很确定这与特定于浏览器的呈现行为有关,这是典型的表单元素。当您在按钮上设置 display: inline
时,我认为发生的事情是……什么都没有。实际上,它与典型的浏览器默认 display: inline-block
相同,width
属性适用。
引用section 10.2 ,它描述了 width
属性本身。特别是它解释了为什么 width
属性不适用于内联元素(或 内联框):
This property does not apply to non-replaced inline elements. The content width of a non-replaced inline element's boxes is that of the rendered content within them (before any relative offset of children). Recall that inline boxes flow into line boxes. The width of line boxes is given by the their containing block, but may be shorted by the presence of floats.
简而言之,这是因为行内元素的内容驻留在行框中。 line box的宽度不能直接控制;它完全由包含 block 和任何附带的 float 决定。您可以在 section 9.4.2 中看到线框渲染的示例。 ,它描述了内联格式化上下文。
如果 display: inline
实际上使按钮呈现为内联框,all its contents would spill over它不再像按钮那样看起来或起作用。想要防止这种情况发生是有道理的,我认为这正是浏览器所做的。
那么他们究竟做了什么来防止这种情况发生呢?按钮是可替换元素吗?我不能肯定地说。但请注意,在 section 9.2.2 中,它说:
Inline-level boxes that are not inline boxes (such as replaced inline-level elements, inline-block elements, and inline-table elements) are called atomic inline-level boxes because they participate in their inline formatting context as a single opaque box.
第 10 节没有明确提及原子行内级框,但它确实有用于计算行内替换元素以及行内 block 元素(无论是否替换)的尺寸的部分,所有这些都被视为原子内联上文提到的。在所有这些情况下,如果 width
属性不是 auto
,它会正常应用。
因此,虽然按钮是否是替换元素仍有争议,但对于这个问题而言,它可能根本无关紧要。但它仍然是某种原子内联元素,因为它仍然参与内联格式化上下文。不过,就其值(value)而言,如果您不设置宽度,它似乎会缩小以适合其内容,因此在这种情况下,它的行为可能更接近内联 block 。那时可以说 actual value display
变为 inline-block
,尽管这从未反射(reflect)在开发人员工具中,因为计算值不会改变(同样是浏览器特定渲染行为的副作用)。
关于html - 为什么宽度适用于带有内联显示的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764419/