inline-block元素没有对齐的解决方案及总结

问题代码:

<div id="frame" style="margin-bottom: 50px">
    <div class="item">test</div>
    <div class="item"></div>
    <div class="item"></div>
</div>

<style>
     .item {
        display: inline-block;
         180px;
        height: 100px;
        background-color: yellow;
     }
</style>

表现如下:

解决办法(两种):

  1. 分别为.item元素设置 vertical-align: top;vertical-align: middle;vertical-align: bottom;

  2. 分别为.item元素设置 overflow: hidden;

解决后表现如下:

问题原因

The baseline of an 'inline-table' is the baseline of the first row of the table.

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.

以上解释来自于: https://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align

以上解释第二条翻译: 一个inline-block元素,如果里面没有inline内联元素,或者overflow不是visible,则该元素的基线就是其margin底边缘,否则,其基线就是元素里面最后一行内联元素的基线。

我们知道,inline-block元素 vertical-align 默认值为 baseline,关于inline-block的baseline属性,网上解释的文章一大堆,解释的也比较详细,我会在文章下方给出链接。我们的布局问题代码中基线为

参考资料

原文地址:https://www.cnblogs.com/hanshuai/p/14979518.html