css 设置margin-top或margin-bottom失效不取作用的解决方法

时间:2016-07-24
在web网站开发中,有时候我们给html元素设置的margin-top或margin-bottom属性,但是无效,并没有取到任何作用,本文章向大家分析margin-top或margin-bottom在哪些情况下会不取作用以及如何解决这些BUG,需要的朋友可以参考一下。

首先来看一个案例:

<!DOCTYPE html>
<html>
<head>
<style>
.bottom-box{
   margin-top:30px; 
}
</style>
</head>
<body>
   <div class="top-box">
      <div class="bottom-box">
        我设置了margin-top属性,我的上边距应该距离父元素为30px;
      </div>    
   </div>
</body>
</html>

可是结果如何呢?结果并不是class为bottom-box的div上边距离父元素30px;而是距离body元素30px;

什么原因呢?

当个子元素设置margin-top属性时,如何父元素没有设置padding属性,即padding属性为0,那么会出现以上这个情况。

解决办法:这里有四种解决办法

  1. 给父元素加上css样式:overflow:hidden
  2. 给父元素加上css样式:padding-top,其值只要不是0都可以
  3. 给父元素加上css样式:position: absolute
  4. 把对父容器的margin-top外边距改成padding-top内边距。

再来看一个实例:

<!DOCTYPE html>
<html>
<head>
<title>http://www.manongjc.com/article/1263.html</title>
<style>
#box{width:600px; background:#E6FECB; border:3px solid #933; overflow:hidden;}
.float_div{float:left; margin:20px; width:100px; height:100px; display:inline; background-color:#CCC;}
</style>
</head>
<body>
<div id="box">
 <div class="float_div"></div>
 <div class="float_div"></div>
 <div class="float_div"></div>
</div>
</body>
</html>

其在IE6和IE7下显示效果为

css 设置margin-top或margin-bottom不取作用的解决方法

margin:20px; 只有margin-bottom失效了。

解决办法:只要在浮动的最后一个元素后面加上“<div class="clear"></div>”,如下:

<!DOCTYPE html>
<html>
<head>
<style>
#box{width:600px; background:#E6FECB; border:3px solid #933; overflow:hidden;}
.float_div{float:left; margin:20px; width:100px; height:100px; display:inline; background-color:#CCC;}
.clear{clear:both;}
</style>
</head>
<body>
<div id="box">
 <div class="float_div"></div>
 <div class="float_div"></div>
 <div class="float_div"></div>
 <div class="clear"></div>
</div>
</body>
</html>

还有个简单点的解决方法:

IE6/7下margin-bottom无效一般出现在容器里某元素设置后在父容器内无效,这个时候只需要在父容器中加入以下两句css,基本上所有的浏览器都兼容了:

overflow:hidden;zoom:100%;

这个方法不用添加额外的标签,也是很好的解决办法!