垂直对齐适用于块元素

Vertical alignment works on block elements

有人告诉我垂直对齐仅适用于内联和 table 元素,但是,今天我在块元素上使用垂直对齐,它工作得很好吗?这怎么可能?在这种情况下,vertical-align 是否适用于所有元素类型?或者,如果不是,它不能用于什么?

#wrap {
border: 1px solid black;
width: 500px;
height: 500px;
}
#alignTop {
vertical-align: top;
border: 1px solid black;
}
<div id = 'wrap'>
<div id = 'alignTop'> alignTop </div>
</div>

默认情况下 block 元素堆叠在彼此之上,因此它 不会 工作。

W3C

In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the 'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.

并且您可以在 W3C 上看到 vertical-alignblock 元素中不起作用,仅适用于 inline-leveltable-cell

Value:    baseline | sub | super | top | text-top | middle | bottom | text-bottom | <percentage> | <length> | inherit
Initial:      baseline
Applies to:   inline-level and 'table-cell' elements
Inherited:    no
Percentages:      refer to the 'line-height' of the element itself
Media:    visual
Computed value:   for <percentage> and <length> the absolute length, otherwise as specified

片段

#wrap {
  border: 1px solid black;
  width: 500px;
  height: 500px;
}
#alignTop {
  vertical-align: top;
  border: 1px solid black;
}
#alignMiddle {
  vertical-align: middle;
  border: 1px solid black;
}
#alignBottom {
  vertical-align: bottom;
  border: 1px solid black;
}
<div id='wrap'>
  <div id='alignBottom'>alignBottom</div>
  <div id='alignTop'>alignTop</div>
  <div id='alignMiddle'>alignMiddle</div>
</div>

根据 This link 上的解释:

  • HTML layout traditionally was not designed to specify vertical behavior. By its very nature, it scales width-wise, and the content flows to an appropriate height based on the available width. Traditionally, horizontal sizing and layout is easy; vertical sizing and layout was derived from that.
  • vertical-align is used to specify two completely different behaviors depending on where it is used

在 table 个单元格中垂直对齐

在 table 单元格中使用时,vertical-align 会做大多数人期望的事情,即模仿(旧的,已弃用的)valign 属性。在符合标准的现代浏览器中,以下三个代码片段执行相同的操作:

  1. <td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
  2. <td style="vertical-align:middle"> ... </td>
  3. <div style="display:table-cell; vertical-align:middle"> ... </div>

内联元素垂直对齐

vertical-align 应用于 内联 元素时,这是一个全新的游戏。在这种情况下,它的行为就像(旧的,已弃用的)align 属性对 <img> 元素所做的那样。在符合标准的现代浏览器中,以下三个代码片段执行相同的操作:

  1. <img align="middle" ...>
  2. <img style="vertical-align:middle" ...>
  3. <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>