css2.1中 firefox 与IE 对margin-top的不同解释

(一)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没有效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>www.Poluoluo.com</title> <style type="text/css"> <!-- * { margin:0; padding:0; } .box1{ float:left; width:500px; height:100px; background:#999; } .box2{ margin-top:20px; width:500px; height:50px; background:#000; color:#fff; clear:both; } --> </style> </head> <body> <div> <div class="box1" >float:left</div> <div class="box2">clear:both; margin-top:20px;</div> </div> </body> </html>
[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;width:500px;background:#000;</div>
</div>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>www.Poluoluo.com.com</title> <style type="text/css"> <!-- * { margin:0; padding:0; } .box2{ margin-top:20px; width:500px; height:50px; background:#000; color:#fff; } --> </style> </head> <body> <div class="box" style="height:100px;background:red;"> <div class="box2">clear:both; margin-top:20px;height:50px;width:500px;background:#000;</div> </div> </body> </html>
[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]

解决办法:

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

转载于:https://www.cnblogs.com/bluers/archive/2012/09/02/2667465.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值