Skip to content

行内框的line-height与vertical-align #4

Description

@stri

先来个例子

    <div style="height:24px;line-height:24px;border:1px solid red;">
     垂直居中?
    </div>

问: 为什么设置height与line-height为相同值的时候,此文本会垂直居中?得先了解下面几个概念。

行框

它与行内框并不是一个概念。在 W3C 中:

In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes. The boxes may be aligned vertically in different ways: their bottoms or tops may be aligned, or the baselines of text within them may be aligned. The rectangular area that contains the boxes that form a line is called a line box.

而且行框的宽度由它的包含块和其中的浮动元素决定。高度的确定由行高计算规则决定。

line-height

这个名词的解释,搜索一大把,CSS手册里的解释: 字体最底端与字体内部顶端之间的距离。不过有下列几点,要单独指出:

  • 它是一行行框的高度;
  • 在W3C中,还有half-leading这个概念,刚看文档时也是一头雾水,后来查了一下,才有点明白,靠谱的解释 在字体排印中「leading」怎么翻译比较合适?CSS 中具体是如何计算的?
  • line-height适用所有元素,它有5种值( normal,number,length,percentage,inherit),默认为normal,其值是相对于字体的一个值(是字体x倍),W3C推荐x值为1.0到1.2之前(据本人测试,chrome的为1.16)
  • 由于half-leading的特征,一般来说,字体相对于其行高,都是在行高之中,上下间距相等,不过由于行高有可能是奇数,字体是偶数,上下间距也可能不相等(有可能差1),不过,大部分情况下都是相等的;

vertical-align

  • 只适用行内框和display为table-cell的元素;
  • 其偏移的计算是相对于当前IFC下的行框来算的;

解释开头的例子

在div中的文字属于行内框(匿名行内框),进行IFC后形成一个行框,此行框的高度继承其父元素的高度为24px,由于line-height的特征,此行框中的文字会居中(其实是相对于此行框,它居中了)。

那么:未知图片垂直居中于容器?

这个可以利用line-height先撑大行框,然后对元素设置vertical-align:middle就可以了,当然这个元素必须符合vertical-align的条件。

PS: IE6下并没有效果,猜测是IE6对line-height的撑开有限制或无效,江湖上还流传着用增大字体大小来解释,其实是一个道理

结语

其实网上还有一大堆奇淫技巧,但理论上,如果要veritcal-align来居中,那肯定跑不掉用方法去撑开行框这一步。

参考资料

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions