進一步理解:inline-block,vertical-align,line-height

看似三個最多見的概念背後卻隱藏了很深的很深「水」
那有多深呢,先來看下面的代碼css

引出問題

<style>
    .inline-block {
      display: inline-block;
    }
    .border {
      border: 1px solid #000000;
    }
    .span {
      width: 100px;
      height: 100px;
    }
    .bak {
      background: #33CCFF;
    } 
    .o-hidden {
      overflow: hidden;
    }
</style>
<div class="border">
   <span class="inline-block border"></span>
</div>
<div class="border">
   <span class="inline-block border span"></span>
</div>
<div class="border">
    <span class="bak inline-block">x</span>
    <span class="inline-block border span"></span>
</div>
<div>
    x
    <span class="inline-block border span">x</span>
    <span class="inline-block border span"></span>
    <span class="inline-block border span o-hidden">xjq</span>
</div>

好,同窗們把這四段代碼放到編輯器裏面而後打開瀏覽器,若是對於你眼前的畫面沒有感到疑惑,那麼其實你就無需向下看了瀏覽器

On a block container element whose content is composed of inline-level elements, ‘line-height’ specifies the minimal height of line boxes within the element. The minimum height consists of a minimum height above the baseline and a minimum depth below it, exactly as if each line box starts with a zero-width inline box with the element’s font and line height properties. We call that imaginary box a 「strut.」 (The name is inspired by TeX.).less

翻譯成國語:編輯器

在一個由行內元素組成的塊級元素中,line-height指定了這個元素中的全部line box的最小高度。這個最小高度包括在baseline上面的最小高度和baseline下面的最小深度,就好像每一個line box是由一個0寬度的,有着元素的font和line-height屬性的行內框開始的,咱們稱這個虛擬的盒子爲strutwordpress

關於baseline和line box的概念請參考張鑫旭大大的文章:
http://www.zhangxinxu.com/wor...spa

看着很亂是吧,上圖來看:翻譯

分析緣由

圖片描述

圖片描述

這是前兩段代碼的示意圖,對比兩張圖發現span沒有寬高的狀況下,baseline上下分別有隱形高度;設置寬高以後,下面的strut仍然存在,再來看第三段代碼的示意圖3d

圖片描述

圖中藍色區域爲行內框的高度,紅線即字母x的baseline,strut的高度正好是紅線到底邊框的高度,也就是說默認垂直對齊方式是baseline;掃了一眼MDN關於vertical-align的文檔,默認值果真是baseline,印證了這一說法。code

看最後一段代碼示意圖:
圖片描述orm

wtf,這又是幾個意思??baseline怎麼又和底邊框接上了??

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.

再來翻譯成國語:

對於一個 inline-block 元素,若是它內部沒有內聯元素,或者它的overflow屬性不是visible,那麼它的baseline就是元素margin的底端。不然,就是它內部最後一個元素的基線。

好了,圖中三個框能夠很好地理解這段話:

最前面的x是用來肯定這個代碼中最外層的div的基線。左起第一個矩形內部有文字,屬於內聯元素,那麼第一個inline-block的基線爲內部x的基線,第二個inline-block的內部無內聯元素,那麼它的基線就是margin的底端,第三個inline-block內部有內聯元素,可是他的overflow屬性爲hidden,不是visible,因此它的基線仍是margin的底端。

解決方案

  1. font-size: 0 或者 line-height: 0

  2. vertical-align !== baseline

方法1和方法2是兩個不一樣的實現思路,方法1是讓strut那個東西消失;方法2提及來就有點多了,簡單理解就是inline-block垂直方向設置非baseline,從而讓strut沒有頂到底部,也就不會有空白出現了

感受本身寫的很亂,有耐心看完的同窗真是謝謝大家了~~

仍是張鑫旭大大寫得好寫的全
http://www.zhangxinxu.com/wor...

相關文章
相關標籤/搜索