嵌套垂直边距折叠如何工作? [英] How do nested vertical margin collapses work?

查看:87
本文介绍了嵌套垂直边距折叠如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解嵌套元素中垂直边缘坍缩的概念。我在)



使用边框,而不是前导文字:( Fiddle


I am having a hard time grasping the concept of vertical margins collapsing in nested elements. I came an article at http://www.howtocreate.co.uk/tutorials/css/margincollapsing explaining how it works however am confused by its explanation. So in its example it cites that there are 2 elements as follows

<div style="margin-top:10px">
<div style="margin-top:20px">
A
</div>
</div>  

Seeing that the inner div has a margin of 20px, that is what will be applied for the entire block of code. What confuses me is everything after that and not yet looking about issues with Internet Explorer 7. Would someone be able to explain it for a complete newbie to CSS in a simplified manner?

解决方案

Two-ish rules to remember:

  1. If margins touch, they collapse.
  2. Nested items "snuggle" if only margin separates them.
  3. Elements outside the "Flow" behave differently. That is, this behavior does not apply the same to floated, or position:fixed, or position:absolute elements.

So for this HTML (nested divs) :

<div id="outer"> 
    <div id="inner">
        A
    </div>
</div> 

and this initial CSS:

#outer {
    margin-top:10px;
    background:blue;
    height: 100px;
}
#inner {
    margin-top:20px;
    background:red;
    height: 33%;   
    width: 33%;
}

The margin collapses to the max of the touching margins and the nested div "snuggles" to the start of the container, like so: (See it at jsFiddle.)

But, the moment the two margins are separated -- by a border or by preceding content in the container, for example -- the margins no longer touch, so they no longer collapse.

EG, just a little, non-breaking white-space , like so:

<div id="outer">&nbsp;
    <div id="inner">
        A
    </div>
</div>

kills the collapse : (See that at jsFiddle.)

Using a border, instead of leading text : (Fiddle)

这篇关于嵌套垂直边距折叠如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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