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;
}
10 2

sub

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

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

参考文章

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

猜你喜欢

转载自www.cnblogs.com/jesse131/p/9079229.html