html - emty inline-block div 之后的元素在顶部有奇怪的填充

标签 html css

<分区>

我想知道自己,为什么具有 display:inline-block 样式的空 div 的行为与包含文本的 div 不同。它似乎以某种方式向以下元素添加了一些无法删除的顶部填充。

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;
}

输出

enter image description here

There's also a fiddle

有人可以解释这种行为吗?

最佳答案

行内元素是vertical-align: baseline默认情况下。基线受文本影响。

改为vertical-align: top / middle / bottom

From the MDN:

baseline

Aligns the baseline of the element with the baseline of its parent. The baseline of some replaced elements, like <textarea> is not specified by the HTML specification, meaning that their behavior with this keyword may change from one browser to the other.

你的新例子

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

关于html - emty inline-block div 之后的元素在顶部有奇怪的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303945/

上一篇:html - 调整包含文本的div的大小

下一篇:css - 具有多个元素的动态宽度

相关文章:

html - 无法正确设置 Flexbox div

css - 如何使用 Flexbox 调整表格单元格取决于最长的单元格

javascript - iframe 之后的文本?

javascript - 网络语音 API : two utterances at same time

php - 使用 CSS 隐藏表格行

html - 如何使用 CSS 设置代码列表的样式?

javascript - require() 和 $ 未在 Electron 中定义

javascript - 在javascript中可以避免这么大的代码块吗?

css - 在 React bootstrap 中更改 Accordion.Header 样式

javascript - 在 HTML 和内部 CSS 中使用 javascript