margin叠加的问题
时间:2009年10月22日作者:愚人码头查看次数:4,468 views评论次数:4
由于margin在浏览器中的BUG很多,有人强烈推荐尽量不要使用margin,而用padding!我很奇怪,我们在前端开发的时候,虽然他们很多时候可以随便用什么,但是很多时候我们不得不用margin。绝大多数的margin引起的BUG是可以解决。
今天有人问我一个margin叠加的问题。有些人喜欢把margin叠加归纳到BUG中去,有些却不这么认为,他们的理由是Firefox也有这个问题,所以不能叫bug。呵呵好像有点牵强。其实大家只要看看w3c的文档,w3c认为margin叠加是合理的。不管是不是bug,但是这个问题真的存在。看下面这个例子:
< !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" />
</head><head>
<style type="text/css">
*{padding:0;margin:0;}
.box{background:#ccc; }
.content{background:#eee;margin: 20px auto;}
.an-box{ margin:50px auto;background:#999999;}
</style>
</head>
<body>
<div class="box">
<div class="content">margin: 20px auto</div>
<div class="content">margin: 20px auto</div>
</div>
<div class="box">
<div class="content">margin: 20px auto</div>
</div>
<div class="box">
<div class="content">margin: 20px auto</div>
</div>
<div class="an-box">margin: 50px auto</div>
</body>
</html>
解决这个问题的方法有不少,先来看看这个,在外层的容器中加:overflow:hidden;zoom:1;
< !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" />
</head><head>
<style type="text/css">
*{padding:0;margin:0;}
.box{background:#ccc; overflow:hidden;zoom:1 }
.content{background:#eee;margin: 20px auto; }
.an-box{ margin:50px auto;background:#999999;}
</style>
</head>
<body>
<div class="box">
<div class="content">这里两个还是存在叠加margin: 20px auto</div>
<div class="content">这里两个还是存在叠加margin: 20px auto</div>
</div>
<div class="box">
<div class="content">margin: 20px auto</div>
</div>
<div class="box">
<div class="content">margin: 20px auto</div>
</div>
<div class="an-box">margin: 50px auto</div>
</body>
</html>
还有外层的容器中加边框属性,在叠加元素加空块状元素等等。。还有就是用padding来取代margin。这里就不说了。
声明: 本文采用 BY-NC-SA 协议进行授权 | WEB前端开发
转载请注明转自《margin叠加的问题》



在叠加元素加空块状元素,我试了不成功。
是这样加吗?
回复麻烦回到我邮箱,谢谢^_^
[回复]
居然屏蔽了我的html代码=.=
我直接在两个content之间加空的div,不成功
[回复]
无标题文档
*{ padding:0; margin:0;}
.div{ background:green; overflow:hidden;zoom:1}
.div1{ background:#ccc; margin:20px auto;}
.div2{ background:#C03; margin:50px auto;}
.div3{ display:inline-block; line-height:0;}/*这个空层使得两个一起叠加的层,不再叠加*/
不存在叠加margin:20px auto;
不存在叠加 margin:20px auto;
margin:20px auto;
margin:20px auto;
margin:50px auto;
[回复]
ヾ左岸の☆の 回复于:八月 9th, 2011 at 4:20 下午
直接在两个content之间加空的div3 样式 .div3{ display:inline-block; line-height:0;} 。在几个浏览器试了下 ,这样貌似解决了两个content还存在叠加的情况。
[回复]