随笔

Baseline with inline block overflow

遇到一个有趣的现象,当子元素设为inline-blockoverflow:hidden会发现父元素的高度被撑开了,理想中的应该是蓝色高度和红色高度重合才对。

<div style="background: red; width: 100px;">
    <div style="
        display: inline-block;
        background: blue;
        overflow: hidden;">
        Sorting
    </div>
</div>

截屏2021-11-04 15.50.41.png

baseline

注意上图中,字母g和旁边的字母相比明显突出下半部分,而突出的这个位置恰好就是baseline,接下来给父元素加一个字母x

截屏2021-11-04 16.13.29.png

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.^1

通过规范说明也印证了表现,inline-block 的元素如果overflow不为visiblebaseline 的位置是底部margin的距离。

strut

顺便看到了另一个有趣的行为,如果把子元素宽高设为 0,但是父元素还是具有宽高。

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.).

继续使用上面的例子,不过需要把文字先移除掉,就得到了下图中的效果。

截屏2021-11-04 16.58.24.png

这时可能会想到既然是line-height撑开的,那把line-height置为 0 不就可以了吗?
看下图是不是有点眼熟,跟上面baseline的到下边框的距离是一样的,所以需要把vertical-align设为top或者bottom。 另外还有一个更简单的,父元素的字体大小设为 0 即可。

截屏2021-11-04 17.02.18.png

本文链接:https://note.lilonghe.net/post/baseline-with-inline-block-overflow.html

-- EOF --