[css学习笔记] inline box & vertical-align

line box & vertical-align

下面是文档中一段关于line box的介绍:

A line box is always tall enough for all of the boxes it contains. However, it may be taller than the tallest box it contains (if, for example, boxes are aligned so that baselines line up). When the height of a box B is less than the height of the line box containing it, the vertical alignment of B within the line box is determined by the vertical-align property.

它讲述的是,line box的高度总是足够高包裹所有内容,而在该line box A中一个高度小于A的box B,则B在A中的垂直方向由vertical-align决定。

vertical-align

而vertical-align的相关介绍是这样说的,vertical-align属性只会在由inline-level元素生成的line box才生效。

This property affects the vertical positioning inside a line box of the boxes generated by an inline-level element.

  • 垂直居中
    所以要想vertical-align:middle实现垂直居中,需要设置display属性把该元素变成行内级元素。
    display: inline || inline-table || inline-block'

vertical-align & line-height

当然vertical-align除了middle还有其他对准基线: baseline | sub | super | top | text-top | bottom | text-bottom | < percentage > | < length > | inherit 。
除了top和bottom是相对于linebox计算以外,其他属性值都是相对于line-height值计算的。
其中,当属性值为百分数时

  • 相对于line-height计算的
    测试一下下面代码看效果会比较容易理解~

    1
    2
    3
    4
    {
    line-height: 30px;
    vertical-align: -10%; //实际值是30px* -10% =-3px,可以实践一下
    }
  • 0%与baseline效果同
    baseline即文字的下边缘。若设置了line-height,在垂直方向上文字的下边缘,而由于font-size和lineheight的共同作用会使文字实现在inlinebox中垂直居中的效果,也就让文字的下边缘出现空白。

    • 真实场景:块状元素中img底部实际上会有小小空白,而这个空白就是inlinebox中的,图片对准的是linebox中的baseline,而至于这里为什么会出现linebox是因为img就是一个inlinebox,则就会隐藏着有一个包裹着它的linebox。
  • 关于baseline和linebox的关系文档是这么说的

    The baseline of an ‘inline-block’ is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its ‘overflow’ property has a computed value other than ‘visible’, in which case the baseline is the bottom margin edge

    如果对这些box的包裹关系有点蒙,可以看这里:inline-block > line box > inline box (以上关系都是相对的)

    1
    2
    3
    4
    <span class="inline-block">
    <img class="inlinebox">
    这里的文字是一个匿名inlinebox。
    </span>

    上文代码中span就是一个inline block,图片和文字分别是两个inline box,都被包裹在同一个line box中。

    回到上面文档的那句话,inline块的baseline取决于它里面的normal flow(忘了看前面概念)中最后一个linebox,除非它没有流内的linebox或者它有一个除了visibleoverflow属性值,则此时它的baseline就是margin-bottom。