码迷,mamicode.com
首页 > 其他好文 > 详细

为什么设置的margin-top属性不管用

时间:2015-12-17 15:37:16      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

为什么设置的margin-top属性不管用:
建议:尽可能的手写代码,可以有效的提高学习效率和深度。
有时候大家可能会遇到奇怪的现象,尽管没有任何的语法错误,但是设置的margin-top属性不会起作用,下面就就结合代码实例介绍一下产生此现象的原因和解决方法。
原因一:
外边距合并margin-top属性失效。代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<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浏览器下不会出现外边距合并现象。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=4638

更多内容可以参阅:http://www.softwhy.com/divcss/

为什么设置的margin-top属性不管用

标签:

原文地址:http://www.cnblogs.com/softwhy/p/5054004.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!