我想知道自己,为什么一个空的div,具有display:inline-block
样式的行为与一个加入文本的div不同。它似乎在某种程度上添加了一些top-padding到以下元素,这些元素无法删除。
HTML
<p>
<div class="a">A</div><div class="b">B</div>
</p>
<p>
<div class="a"></div><div class="b">B</div>
</p>
CSS
.a {
width:20px;
height:20px;
display:inline-block;
background-color:red;
}
.b {
background-color:orange;
line-height:20px;
font-size:12px;
display:inline-block;
}
输出
有人可以解释这种行为吗?
答案 0 :(得分:1)
内联元素为vertical-align: baseline
。基线受文本影响。
更改为vertical-align: top / middle / bottom
基线
将元素的基线与其父元素的基线对齐。 HTML规范未指定某些替换元素的基线,如
<textarea>
,这意味着它们对此关键字的行为可能会从一个浏览器更改为另一个浏览器。
.a {
width: 20px;
height: 20px;
display: inline-block;
background-color: red;
vertical-align: top;
}
.b {
background-color: orange;
line-height: 20px;
font-size: 12px;
display: inline-block;
vertical-align: top;
}
br {
line-height: 2;
}
<div class="a">A</div>
<div class="b">B</div>
<br />
<div class="a"></div>
<div class="b">B</div>