div嵌套margin-top失效的解决方法

近日学习过程中,出现一个问题:内外多层div嵌套时,margin-top不起作用,margin-left起作用,查询百度,有结果:

当两个容器嵌套时,如果外层容器和内层容器之间没有别的元素,firefox会把内层元素的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=gb2312" />
<title>div嵌套内层margin-top不起作用</title>
<!--
div嵌套内层margin-top不起作用
@author:yard39@163.com
原因:当两个容器嵌套时,如果外层容器和内层容器之间没有别的元素,firefox会把内层元素的margin-top作用与父元素。
-->
<style type="text/css">
    .outer{
    width:500px;
    height:400px;
    background-color:#ccc;
    /*解决方法一:外层加float
    float:left;*/
    /*解决方法二,外层用padding,但内层不能再设置margin-top,否则间距会相加
    padding-bottom:20px;*/
    /*解决方法三:给外层加个边框,可以设置边框颜色与周围一致
    border:1px  dashed #333;*/
    /*综合来看,第一种方法要记得后面加clear,第二种方法容易引起兼容性问题,第三种方法带边框可能不合使用要求,第四种方法推荐*/
    }
    .inner{
    width:300px;
    height:200px;
    background-color:#333;
    margin-top:20px;
    margin-left:20px;
    }
</style>
</head>
<body>
    <div class="outer">
        <!--内外层之间没有元素-->
        <!--解决方法四:在内层之上加入下面的代码:
        <div style="height:0px;">&nbsp;</div>-->
        <div class="inner">
        </div>
    </div>
</body>
</html>

 

posted on 2015-07-02 10:54  yard39  阅读(386)  评论(0编辑  收藏  举报