您的位置:首页 > Web前端 > CSS

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

2012-09-02 13:18 381 查看
(一)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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: