没有高度的inline-block,父元素却有高度

一个div里面放有一个inline-block的元素,该元素没有宽高,但父元素却被撑开18px,求解释

<div class="parent">
    <div style="display: inline-block;">
</div>

clipboard.png

阅读 14.3k
5 个回答

line-block 没有内容的时候,会根据 font 产生一个 line-height 来产生一个空白块。

解决方法:

<div class="parent" style="font-size: 0;">
    <div style="display: inline-block;">
</div>

这是因为 line box 的最小高度是由一个叫 strut 的假想块决定的。

当 line box 为空时,高度当 0 处理,见 9.4.2

Line boxes that contain no text, no preserved white space, no inline elements with non-zero margins, padding, or borders, and no other in-flow content (such as images, inline blocks or inline tables), and do not end with a preserved newline must be treated as zero-height line boxes for the purposes of determining the positions of any elements inside of them, and must be treated as not existing for any other purpose.

否则 line box 就会计算高度(如问题中有了 inline-block 子元素),按这里。因为那个 inline-block 没有高度,故直接看第三步

The line box height is the distance between the uppermost box top and the lowermost box bottom. (This includes the strut, as explained under 'line-height' below.)

那个 inline-block 默认放在 baseline 上,其高度是由 line-heightfont-size 属性决定的。具体看浏览器的默认样式。

按我的理解,这里面涉及到两个知识点:1. BFC(由显示的声明display: inline-block产生),2. 各个浏览器默认样式。
在Chrome浏览器下测试结果如下:

  1. 默认情况下:

图片描述

2.设置line-height: 0
图片描述

3.设置height: 0
图片描述

4.子元素设置display: inline,或者不声明这个属性:
图片描述

简而言之,就是子元素设置了display:inline-block;导致了BFC,撑开了parent的高度,但是由于子元素没有任何内容,那么parent高度就由各个浏览器下默认样式决定(受height/line-height/font-size等影响)。

没有格式化CSS,浏览器会渲染出默认div所有的边距

图片描述

一张图说明,因为把inline-block的元素放在baseline(即xza这些字母下端的这条线)上了,由于父元素是没有高度的,所以你把有高度的子元素放在基线上,自然就会撑起来后多出一块。如果vertical-align: bottom或者vertical-align: top就没有了多出的一块了。或者可以把父元素的font-size设为0,那么baseline就和bottom在一条线上了。不管你实际上有没有文字内容,实际上都会假想你有文字,即使你没有文字基线也是在那里。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题