html - 两个div同一行: why overflow: hidden; causes vertical offset?

标签 html css

我有两个 div 一个挨着一个坐在同一行上,display: inline-block; https://jsfiddle.net/3q0kbv2k/ .当我将 overflow: hidden; 放在第一个 div 上时,第二个 div 向下移动了一个小的偏移量。

HTML:

<!-- CODE ON ONE LINE ON PURPOSE -->
<!-- WHITESPACES BREAK LAYOUT -->
<div class="foo">foooooooooooooooooooooo</div><div class="bar"><div>bar</div></div>

CSS:

.foo {
    display: inline-block;
    width: 9%;
    margin-right: 1%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    background: red;
}

.bar {
    display: inline-block;
    width: 90%;
    background: yellow;
}

为什么会这样?

我找到了 this old question它描述了完全相同的场景并包含解决方法,但我有兴趣了解为什么会发生这种情况,这是错误还是正常行为?

最佳答案

来自spec :

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.

您的 foo div 有一个“不可见”的溢出,因此它的基线是“底部边距边缘”。

您的 bar div 有可见的溢出,所以它的基线就是它的文本的基线。

您可以通过为它们提供相同的 vertical-align 样式来解决此问题:

.foo {
    display: inline-block;
    width: 5%;
    margin-right: 1%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    background: red;
    vertical-align: middle;
}

.bar {
    display: inline-block;
    width: 90%;
    background: yellow;
    vertical-align: middle;
}
<div class="foo">foooooooooooooooooooooo</div>
<div class="bar"><div>bar</div></div>

关于html - 两个div同一行: why overflow: hidden; causes vertical offset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887531/

相关文章:

javascript - 如何通过单击图像打开文本?

css - 删除内联元素之间的填充

javascript - 如何暂停 JavaScript 动画事件

html - CSS:从父级撤销透明颜色

javascript - 我的导航栏上的显示/隐藏按钮 Bootstrap 不起作用

javascript - 如何使用 Javascript 获取 DIV 元素的顶部(如在语言环境中)属性?

html - 悬停在多个 div 上

html - Box Shadow 在 Chrome 中有效,但在 IE 和 Firefox 中无效

jquery - 给 jQuery 创建的文本它自己的专有属性

css - 图像在窗口调整大小时调整大小?