1 ,初始代码如下:
<body style="border: 2px solid blue;">
<div id="container" style="height: 200px; background-color: gray; ">
<p style="margin-top: 0px; height: 20px; background-color: red;">test</p>
</div>
</body>
效果:
2,修改一下p元素的margin-top为100px 如下:
<body style="border: 2px solid blue;">
<div id="container" style="height: 200px; background-color: gray; ">
<p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
</div>
</body>
效果如下:
p元素的margin似乎变成了div元素的magin
3,在p元素前加了内容,代码:
<body style="border: 2px solid blue;">
<div id="container" style="height: 200px; background-color: gray; ">
<p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
</div>
</body>
效果如下:
这下正常了,margin还给p元素了,但是, 因为加了空行,所以距离不是100px了... 不可取的解决方案。
科学的解决方法:
<body style="border: 2px solid blue;">
<div id="container" style="height: 200px; background-color: gray; overflow: hidden;">
<p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
</div>
</body>
=====================================================
进入正题: 这是什么原因,以及如何解决。
原因分析: 同一个BFC内,垂直方向盒子的上下会出现margin重叠