我遇到了父div高度大于内容的问题,我正在努力理解原因。
特别是子div有display:inline块,没有内容。填充、边距、边框均为0;
有趣的是,添加任何内容,甚至是nbsp,都可以解决问题。
这是浏览器错误还是设计错误?
why parent div height is larger than child div?
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block'></div>
</div>
<hr>
adding any content fixes sizing
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block'>
x
</div>
</div>
& nbsp; works too
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block'> </div>
</div>
它是经过设计的,与基线对齐有关。要了解发生了什么,请在容器中添加更多文本
why parent div height is larger than child div?
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block'></div>
p
</div>
<hr>
adding any content fixes sizing
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff'>
x
</div>
p
</div>
& nbsp; works too
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff'> </div>
p
</div>
在这3种情况下,inline-block
与基线对齐,但空inline-block
元素的基线是其底边,因此您有用于下行的底部空间。
"内联块"的基线是其在正常流中的最后一个行框的基线,除非它没有流中的行框,或者如果它的"溢出"属性的计算值不是"可见",在这种情况下,基线是底边ref
如果添加oveflow:hidden
,在这3种情况下也会出现此问题
why parent div height is larger than child div?
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;overflow:hidden'></div>
p
</div>
<hr>
adding any content fixes sizing
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff;overflow:hidden'>
x
</div>
p
</div>
& nbsp; works too
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff;overflow:hidden'> </div>
p
</div>
为了避免这种情况,你只需将对齐方式更改为与基线不同的方式:
why parent div height is larger than child div?
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;overflow:hidden;vertical-align:top;'></div>
p
</div>
<hr>
adding any content fixes sizing
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff;overflow:hidden;vertical-align:top;'>
x
</div>
p
</div>
& nbsp; works too
<div style="background-color:red;">
<div style='background-color:blue; width:32px; height:32px; display:inline-block;color:#fff;overflow:hidden;vertical-align:top;'> </div>
p
</div>
相关:
为什么这个内联块元素被向下推?
div内部的图像在图像下方有额外的空间