嵌套div产生滚动条。为什么? [英] Nested divs producing a scrollbar. Why?

查看:427
本文介绍了嵌套div产生滚动条。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个嵌套div:

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

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

  .outer {
width:50%;
height:100px;
border:1px纯红色;
职位:亲属;
overflow-x:hidden;
box-sizing:border-box;
}
.inner {
border:1px solid blue;
身高:100%;
位置:绝对;
box-sizing:border-box;
}
.item {
width:100px;
身高:100%;
background-color:yellow;
display:inline-block;
border:1px纯绿色;
box-sizing:border-box;
}

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



以下是 codepen



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



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

解决方案

这是因为您的 .item 元素设置为显示为 inline-block 。这意味着它受到诸如 line-height vertical-align 之类的影响。



inline-block 元素的默认垂直对齐是基线。这意味着它们被设置为出现在可能与其一起输入的任何文本的基线上。我不是100%确定的,但我认为可能存在这样的问题,在进行此计算时忽略框大小,并且基线结束为2像素以下它应该在哪里(因为元素的顶部和底部应用了边框的累积2像素)。

如果您希望该元素保持以这种方式显示,一个快速解决方案是将其 vertical-align 设置为 top

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

Codepen演示


I have 3 nested divs:

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

The .inner div is position absolute and they each have 1px border:

.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;
}

This arrangement results in a scrollbar on the .outer div.

Here's a codepen

Why is this and what do I need to change to stop it happening?

If the width of the border of the .inner div is increased to 3px then the scrollbar goes away. Again, why is this happening?

解决方案

This is happening because your .item element is set to display as an inline-block. This means it's affected by things like line-height and vertical-align.

The default vertical alignment on inline-block elements is baseline. This means they're set to appear at the base line of any text that may be entered alongside it. I'm not 100% sure but I think there may be an issue here where box-sizing is ignored when making this calculation, and the base line ends up being 2 pixels below where it should be (due to the cumulative 2 pixels of border applied to the top and bottom of the element).

If you want that element to remain being displayed this way, a quick fix is to set its vertical-align to top:

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

Codepen demo.

这篇关于嵌套div产生滚动条。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆