嵌套div中margin-top转移问题的解决办法

[文章来源于网络]

两个嵌套关系的div,如果外层div的父元素padding值为0,那么内层div的margin-top或者margin-bottom的值会“转移”给外层div。

<!doctype html>
<head>
<meta charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<div style="background-color:#FF0000;width:300px;height:100px">上部层</div>

<div style="background-color:#009900; width:300px;height:300px"><!--父层-->
 
   <div style="margin:50px;background-color:#000000;width:200px;height:200px">子层</div>
</div>

</body>
</html>

原因:盒子没有获得 haslayout  造成margin-top无效 

垂直margin可能在一些盒模型中被折叠:

1、在常规文档流中,2个或以上的块级盒模型相邻的垂直margin会被折叠。
最终的margin值计算方法如下:
a、全部都为正值,取最大者;
b、不全是正值,则都取绝对值,然后用正值减去最大值;
c、没有正值,则都取绝对值,然后用0减去最大值。
注意:相邻的盒模型可能由DOM元素动态产生并没有相邻或继承关系。

 

解决办法:

1、在父层div加上:overflow:hidden;

2、把margin-top外边距改成padding-top内边距 ;

3、父元素产生边距重叠的边有不为 0 的 padding 或宽度不为 0 且 style 不为 none 的border。

   父层div加: padding-top: 1px;

4、让父元素生成一个 block formating context,以下属性可以实现
    * float: left/right
    * position: absolute
    * display:inline-block/table-cell(或其他 table 类型)
    * overflow: hidden/auto

   父层div加:position:absolute;


原文地址:http://www.moonless.net/blog/2007/09/css21831collapsing-marginscollapsing.html
英文地址:http://www.w3.org/TR/CSS21/box.html#collapsing-margins