html - 为什么这个内联 block 元素的内容没有垂直对齐

标签 html css vertical-alignment

遇到一个奇怪的 CSS 问题。有人可以解释为什么包含内容的框没有垂直对齐吗?

如果您将文本放入 .divPutTextToFixIssue 类的范围内 - 它会正确对齐。

http://jsfiddle.net/KgqJS/88/

   #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/

相关文章:

html - 使用 flex : 1 auto;

javascript - localStorage 如何保存复选框

html - 行高和字体大小的变化导致内联 block 元素中出现间隙

html - 如何水平和垂直对齐内联 block

HTML/CSS - 将 ul 在 block 元素中垂直居中

javascript - 如何绑定(bind)多个元素一起滚动?

html - CSS负背景图片

html - 对齐输入并在同一行中选择(bootstrap mobile)

css - Internet Explorer 7 中的@font-face 问题

html - 添加左浮动 <ul> 后表格单元格内容不垂直对齐