遇到一个奇怪的 CSS 问题。有人可以解释为什么包含内容的框没有垂直对齐吗?
如果您将文本放入 .divPutTextToFixIssue 类的范围内
- 它会正确对齐。
#divBottomHeader {
background-color: #d5dbe0;
height: 43px;
}
.divAccountPicker {
display: inline-block;
background: blue;
width: 200px;
height: 40px;
}
.divAccountData {
display: inline-block;
background: red;
width: 400px;
height: 40px;
}
<div id="divBottomHeader">
<div class="divAccountPicker">
<span class="divPutTextToFixIssue"></span>
</div>
<div class="divAccountData">
<span>Balance: $555</span>
</div>
</div>
最佳答案
默认 vertical-align
值为 baseline
哪个
Aligns the baseline of the box with the baseline of the parent box
注意:您可以通过添加 vertical-align:baseline
来查看此默认值的实际效果。给你的.divAccountData
选择器。自 baseline
默认对齐方式不变。
您需要将其更改为top
对齐顶部的 block ,例如:
.divAccountData {
display: inline-block;
background: red;
width: 400px;
height: 40px;
vertical-align: top;
}
Baseline定义为
the line upon which most letters "sit" and below which descenders extend
解决为什么添加文本似乎可以解决问题的原因是
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.
来自 CSS2 Visual formatting model details
所以只添加一个字符会改 rebase 线,导致第二个 block 出现在相同的垂直对齐方式上。这仅在两个 block 包含相同行数的情况下有效。尝试向您的 block 之一添加更多单词,您会看到无需强制 vertical-align:top
在第二个 block 上,它将根据第一个 block 中存在的文本行数移动。
编辑:找到一个相关问题Why is this inline-block element pushed downward?
关于html - 为什么这个内联 block 元素的内容没有垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950479/