Vertical-Align属性探究

在前端开发中我们经常需要将元素垂直居中对齐,我们很自然的想到使用 vertical-align 属性,但是使用后却发现有时候能起作用,有时候却又不起作用。究其原因还是因为我们没有将 vertical-align 属性弄清楚,今天就来分析一下这个属性,若分析有误,还请原谅,望一起探讨!

规范介绍

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

适用元素

该属性仅适用于 inline,inline-block,table-cell 元素

属性值介绍

介绍属性之前先来了解一下各个属性值代表着什么,通过下面这张图可以知道
英语本子4条线
我们知道英语本子每行有 4 条线,其中红色的线即为基线

所用 demo

<div class="box">
  <span class="aa"></span>
  x
</div>

baseline

将元素的基线与父元素的基线对齐

.aa4 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: baseline;
}
x

baseline 的确定规则

  1. inline-table 元素的 baseline 是它的 table 第一行的 baseline。
  2. 父元素【line box】的 baseline 是最后一个 inline box 的 baseline。
  3. inline-block 元素,如果内部有 line box,则 inline-block 元素的 baseline 就是最后一个作为内容存在的元素[inline box]的 baseline,而这个元素的 baseline 的确定就要根据它自身来定了。
  4. inline-block 元素,如果其内部没有 line box 或它的 overflow 属性不是 visible,那么 baseline 将是这个 inline-block 元素的底 margin 边界。

length

基于基线上(正值)下(负值)移动元素

input[name="sex"] {
  margin: 0;
  padding: 0;
  vertical-align: -2px;
}

基于基线向下移动-2px

女性男性

percentage

基于基线上(正值)下(负值)移动元素,值通过百分比乘上 line-height 而得

.aa2 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: -10%;
  line-height: 30px;
}
x

这里的 vertical-align:-10%所代表的实际值是:-10% * 30 = -3px,即向基线下方移动 3px
注意:若该元素没有定义 line-height,则会使用继承的line-height

middle

将元素的中线与父元素的基线加上字母 x 的高度的一半对齐

.aa3 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: middle;
}
x

text-top

将元素的顶部与父元素正文区域的顶部对齐,元素的位置受父元素 font-size 的大小影响

.aa5 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: text-top;
}
x

text-bottom

将元素的底部与父元素的正文区域的底部对齐,元素的位置受父元素 font-size 的大小影响

.aa6{
    display:inline-block;
    width:5px;
    height:5px;
    background:blue;
    vertical-align: text-bottom;
}
x

top

将元素的顶部与 line box 顶部对齐

.aa7 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: top;
}
x

bottom

将元素的底部与 line box 底部对齐

.aa8 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: bottom;
}
x

super

将元素置于基线上方合适的位置

.aa10 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: super;
}
102

sub

将元素置于基线下方合适的位置

.aa9 {
  display: inline-block;
  width: 5px;
  height: 5px;
  background: blue;
  vertical-align: sub;
}
x

参考文章

vertical-align
vertical-align
我对 CSS vertical-align 的一些理解与认识(一)