1 ,初始代码以下:html
<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>布局
效果:flex
2,修改一下p元素的margin-top为100px 以下:spa
<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>orm
效果以下:htm
p元素的margin彷佛变成了div元素的maginblog
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>io
效果以下:class
这下正常了,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重叠