原因一:
外边距合并margin-top属性失效。代码实例如下:

<!DOCTYPE html>
<html>
<head>
<  http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<  name=\"author\" content=\"http://www.softwhy.com/\" />
< >蚂蚁部落</ >
<style type=\"text/css\">
.first{
  width:100px;
  height:100px;
  background-color:red;
  margin-bottom:60px;
}
.second{
  width:100px;
  height:100px;
  background-color:green;
  margin-top:40px;
}
</style>
</head>
<body>
<div class=\"first\"></div>
<div class=\"second\"></div>
</body>
</html>

从以上代码的运行可以看出,第二个div设置的margin-top并没有生效,起作用的是第一个div的设置的margin-bottom,这里有个规律,那就是合并后的外边距的高度等于外边距的高度中的较大的一个,所以遇到此种情况可以格外注意外边距大小的设置。

 

原因二:
子元素和父元素也可能会导致设置的子元素上外边距失效情况,代码实例如下:

<!DOCTYPE html>
<html>
<head>
<  http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<  name=\"author\" content=\"http://www.softwhy.com/\" />
< >蚂蚁部落</ >
<style type=\"text/css\">
.father{
  width:300px;
  height:300px;
  background-color:red;
  margin-top:20px;
}
.children{
  width:100px;
  height:100px;
  background-color:blue;
  margin-top:10px;
}
</style>
</head>
<body>
<div class=\"father\">
  <div class=\"children\"></div>
</div>
</body>
</html>

解决方法:
为父对象在相应的外边距方向上有边框(border)和内边距(padding),或者为overflow属性值设置为hidden即可避免。
IE6浏览器下不会出现外边距合并现象。

收藏 打印