css2.1中 firefox 与IE 对margintop的不同解释

(一)margin-top失效  
   先看下面代码:<div>
<div class="box1" >float:left</div>
<div class="box2">clear:both; margin-top:20px;</div>
</div>

  两个层box1和box2,box1具有浮动属性,box2没有,这时候设置box2的上边距 margin-top没有效果


[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]

 网上能找到的两种比较靠谱的解释:1:“在css2.1中,水平的margin不会被折叠;垂直margin可能在一些盒模型中被折叠…”2:当第一个层浮动,而第二个没浮动层的margin会被压缩,详见--浮动元素后非浮动元素的margin的处理(地址)。

得到解决问题思路:要浮动一起浮动,要就一起不浮动。

解决办法:

1.box2增加float属性
2.box1与box2之间增加一层"<div style="clear:both;"></div>"

  (二)子元素设置margin-top作用于父容器

<div class="box" style="height:100px;background:red;">
  <div class="box2">clear:both; margin-top:20px;height:50px;500px;background:#000;</div>
</div>

当给box2设置margin-top时,在FF下仅作用于父容器。


[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]

解决办法:

1.给父容器box加overflow:hidden;属性
2.父容器box加border除none以外的属性
3.用父容器box的padding-top代替margin-top

原文地址:https://www.cnblogs.com/bluers/p/2667465.html