margin-top使用需要注意的地方

偶然的机会发现一个有趣的现象:一个div(背景色为绿色)里面包含一个div,里面的div给一个margin-top:100px;

代码:

<div style="background: green">
  <div style="background: blanchedalmond;margin-top:100px; height:300px"></div>
</div>

我想的是会撑高父级div的高度,露出绿色的背景色,但是实际显示效果却是它连同父级一起下移了;预想的效果和实际效果:

预想的效果:

但是实际的效果(灰色为body的背景色):

当给父级div中加上内容之后效果显示正常了,代码:

<div style="background: green;">
  test
  <div style="background: blanchedalmond;margin-top:100px; height:300px"></div>
</div>

效果:

最后想出一个解决的方法:给父级加上一个overflow:hidden;

但是遗留了一个问题,“这到底是为什么呢,这样不是违背了盒模型设计吗~~”

原文地址:https://www.cnblogs.com/wangrongxiang/p/5711003.html