單行高度
一行文字的高度等於 font-size 乘以 line-height
font-size: 14px, line-height: 1
當行高設置為 1 時,行高度是:
14 * 1 = 14px
font-size: 14px, line-height: 1.5
調整到 1.5 時,行高度是:
14 * 1.5 = 21px
文字行內間距
文字在一行裡的上下間距等於 font-size * (line-height - 1) * 0.5
line-height: 1
行高設為 1 時,文字上下沒有間距,調到 1.5 倍以後的效果:
line-height: 1.5
行高變成了 21px,文字上下間距是:
(21 - 14) * 0.5 = 3.5px
用字號和行高的關係計算出間距:
14 * (1.5 - 1) * 0.5 = 3.5px
多行文字
總高度 = 單行高度 * 行數
font-size: 14px, line-height: 1.5
5 行文字的高度是:
14 * 1.5 * 5 = 21 * 5 = 105px
行與行之間的間距是:
14 * (1.5 - 1) = 7px
行間距和字號計算行高的方法:
1 + 行間距 / 字號 = 行高
1 + 7 / 14 = 1.5
行高帶來的排版問題
文本在行內部上下的間距,隨著行高的增加會變得更加明顯。
font-size: 14px, line-height: 2.0
當行高設置為 2 倍時,上下空白的間距達到了 7px,這個距離會拉大文字和上一個元素的間距。
div 的 margin-bottom: 24px
文字和上一個元素的實際間距就是 24 + 7 = 31px,期望的排版效果是下面這樣的:
期望的效果
解決方案
利用外邊距摺疊(Collapsing Margins)可以解決這個問題。
使用字號和行高可以計算出上下的空白間距,字號 14px、行高 2.0 ,那麼間距就是:
14 * (2 - 1) * 0.5 = 7px
那麼只要給文字的 ::before 偽元素設置 margin-top: -7px ,在外邊距摺疊效果下文字就會上移 7px,剛好就消除了上間距。
對於底部空白邊距,就給 ::after 偽元素設置 margin-bottom: -7px,讓下面的元素位置上移 7px,就可以抵消下間距。
看一下 CSS 代碼和效果:
.markdown-body > p::before { content: ""; display: block; width: 0; height: 0; margin-top: -7px;}::before margin-top: -7px
.markdown-body > p::after { content: ""; display: block; width: 0; height: 0; margin-bottom: -7px;}::after margin-bottom: -7px
(全文完)