看似三個最常見的概念背后卻隱藏了很深的很深“水”
那有多深呢,先來看下面的代碼
引出問題
<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.).
翻譯成國語:
在一個由行內元素組成的塊級元素中,line-height指定了這個元素中的所有line box的最小高度。這個最小高度包括在baseline上面的最小高度和baseline下面的最小深度,就好像每個line box是由一個0寬度的,有著元素的font和line-height屬性的行內框開始的,我們稱這個虛擬的盒子為strut
關于baseline和line box的概念請參考張鑫旭大大的文章:
http://www.zhangxinxu.com/wor...
看著很亂是吧,上圖來看:
分析原因
這是前兩段代碼的示意圖,對比兩張圖發現span沒有寬高的情況下,baseline上下分別有隱形高度;設置寬高之后,下面的strut仍然存在,再來看第三段代碼的示意圖
圖中藍色區域為行內框的高度,紅線即字母x的baseline,strut的高度正好是紅線到底邊框的高度,也就是說默認垂直對齊方式是baseline;掃了一眼MDN關于vertical-align的文檔,默認值果然是baseline,印證了這一說法。
看最后一段代碼示意圖:
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的底端。
解決方案
font-size: 0 或者 line-height: 0
vertical-align !== baseline
方法1和方法2是兩個不同的實現思路,方法1是讓strut那個東西消失;方法2說起來就有點多了,簡單理解就是inline-block垂直方向設置非baseline,從而讓strut沒有頂到底部,也就不會有空白出現了
感覺自己寫的很亂,有耐心看完的同學真是謝謝你們了~~
還是張鑫旭大大寫得好寫的全
http://www.zhangxinxu.com/wor...