我有两个 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/