带有边距顶部集合的嵌套div会导致滚动条出现 [英] Nested div with margin top set causes scrollbar to appear

查看:110
本文介绍了带有边距顶部集合的嵌套div会导致滚动条出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个小的HTML片段:

 < div id =outer> 
< div id =inner>
< div id =inner2> foo bar< / div>
< / div>
< / div>

我也定义了这些样式:

  #outer {
height:100px;
overflow:auto;
background-color:#EEE;
}
#inner {
height:100px;
background-color:#AAA;
}
#inner2 {
margin-top:5px;
}

使用此设置,滚动条会显示 div:





为什么嵌套的内部div会导致此滚动条出现?



我可以删除滚动条删除 margin-top 规则,但这将导致副作用。



这里是一个jsfiddle重现问题: http ://jsfiddle.net/stevebeauge/PTA85/



[edit] :我的实际问题是通过将 margin-top padding-top ,但我正在寻找一个解释,

解决方案

这是因为边距正在折叠


框模型8.3.1折叠边距



在CSS中,两个或多个框(可能是或不是兄弟)的邻接边距可以组合形成一个边距。



当两个或多个边距合拢时,生成的边距宽度为最大值的折叠边距宽度。在负余量的情况下,负相邻余量的绝对值的最大值从正相邻余量的最大值中扣除。如果没有正边距,则相邻边距的绝对值的最大值从零中扣除。


可能的解决方法: p>

将边距替换为填充(示例)。 p>

添加 overflow:auto #inner (example)



Float #inner2 (示例)



#inner2 的显示从更改为 inline-block (示例)



有关更多信息,请参阅视觉格式模型 - 阻止格式化上下文


Let's say I have this small HTML snippet:

<div id="outer">
    <div id="inner">
        <div id="inner2">foo bar</div>
    </div>
</div>

I also have these styles defined:

#outer {
    height:100px;
    overflow:auto;
    background-color:#EEE;
}
#inner {
    height:100px;
    background-color:#AAA;
}
#inner2 {
    margin-top:5px;
}

With this setup, scroll bars appears with the outer div:

Why does the nested inner div causes this scrollbar to appears?

I can remove the scrollbar by removing the margin-top rule, but this would cause side effects.

Here is a jsfiddle that reproduces the issue: http://jsfiddle.net/stevebeauge/PTA85/

[edit]: my actual issue is solved by replacing margin-top by padding-top, but I'm looking for an explanation, not only the solution.

解决方案

This is occurring because the margins are collapsing.

Box Model 8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins' widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

Possible workarounds:

Replace the margin with padding (example).

Add overflow:auto to #inner (example)

Float #inner2 (example)

Change the display of #inner2 from block to inline-block (example)

For additional information see The visual formatting model - Block formatting contexts.

这篇关于带有边距顶部集合的嵌套div会导致滚动条出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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