5

我有 3 个嵌套的 div:

<div class="outer">
  <div class="inner"><div class="item"></div></div>
</div>

.inner div 是绝对位置,它们每个都有 1px 边框:

.outer{
  width:50%;
  height:100px;
  border: 1px solid red;
  position:relative;
  overflow-x:hidden;
  box-sizing:border-box;
}
.inner{
  border:1px solid blue;
  height:100%;
  position: absolute;
  box-sizing: border-box;
}
.item{
  width:100px;
  height:100%;
  background-color:yellow;
  display: inline-block;
  border:1px solid green;
  box-sizing:border-box;
}

这种安排会在 .outer div 上产生一个滚动条。

这是一个代码笔

为什么会这样,我需要改变什么来阻止它发生?

如果 .inner div 的边框宽度增加到 3px,那么滚动条就会消失。再次,为什么会发生这种情况?

4

4 回答 4

4

发生这种情况是因为您的.item元素设置为显示为inline-block. 这意味着它会受到 和 之类的line-height影响vertical-align

元素的默认垂直对齐方式inline-block是基线。这意味着它们将出现在可以在其旁边输入的任何文本的基线处。我不是 100% 确定,但我认为这里可能存在一个问题,box-sizing在进行此计算时会被忽略,并且基线最终会比应有的位置低 2 个像素(由于累积 2 个像素的边框应用于元素的顶部和底部)。

如果您希望该元素保持以这种方式显示,快速解决方法是将其设置vertical-aligntop

.item {
    ...
    vertical-align: top;
}

Codepen 演示

于 2015-10-07T14:40:36.277 回答
2

The weirdest thing is that if you remove overflow-x:hidden; the scrollbar goes away. The reason is that the default behavior of overflow is visible thus if you don't mess with it, the results will be no scrollbars, but setting overflow-x to some value, sets overflow-y to auto instead of the default value which is visible and as a result, the scrollbar appears.

If you set overflow to auto the scrollbar will also appear.

On the other hand, .item is set to inline-block so it has line-height which produces the space on the bottom. Setting .inner to line-height:0 will make the space disappear, and if you increase it it will increase as well.

On the other ( third hand ) you can just constrict the space that the elements inside .inner take by setting .inner to overflow:hidden

于 2015-10-07T14:49:09.267 回答
0

为什么你inline-block在内部项目中使用?如果您更改为阻止您的滚动消失:

.item{
  width:100px;
  height:100%;
  background-color:yellow;
  display: block;
  border:1px solid green;
  box-sizing:border-box;
}
于 2015-10-07T14:39:39.340 回答
-1

It's because your height is 100% then you're adding 1px of border on each div. Working demo: http://codepen.io/anon/pen/VvbNXp

So your .inner and .item classes need the height changed to:

height:calc(100% - 1px);
于 2015-10-07T15:01:19.877 回答