margin塌陷问题
当两个盒子在垂直方向上设置margin值时,会出现一个有趣的塌陷现象。
1、垂直并列
首先设置两个DIV,并为其制定宽高和背景色方便观看
<style>
/*CSS部分*/
*{
margin: 0;
padding: 0;
}
.box1{
width: 200px;
height: 200px;
background-color: aquamarine;
}
.box2{
width: 200px;
height: 200px;
background-color: bisque;
}
</style>
</head>
<body>
<!--html部分-->
<div class="box1">box1</div>
<div class="box2">box2</div>
</body>
对box1我们为其设置margin-bottom:50px;
对box2我们为其设置margin-top: 40px;
<style>
/*CSS部分*/
*{
margin: 0;
padding: 0;
}
.box1{
width: 200px;
height: 200px;
margin-bottom: 50px;
background-color: aquamarine;
}
.box2{
width: 200px;
height: 200px;
margin-top: 40px;
background-color: bisque;
}
</style>
</head>
<body>
<!--html部分-->
<div class="box1">
box1
</div>
<div class="box2">
box2
</div>
</body>
我们肯定会很理所当然的认定这两个盒子之间的距离为90px,事实上并非如此.
如下图所示:
两盒子之间的距离仅是50px,也就是说两盒子之间的margin出现了重叠部分,故而我们可以得出:垂直之间塌陷的原则是以两盒子最大的外边距为准。
2、嵌套关系(父级元素塌陷)
<style>
/*css部分*/
*{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 400px;
background-color: aliceblue;
}
.box1{
width: 250px;
height: 250px;
background-color: bisque;
}
</style>
</head>
<body>
<!--html部分-->
<div class="box">
<div class="box1"></div>
</div>
</body>
效果图
当为子盒子添加margin-top:100px;时会发生如下情况:
子盒子和父盒子之间并没出现期望的10px间隙而是父盒子与子盒子一起与页面顶端产生了10px间隙(即父级盒子往下塌陷了10px)。
解决方法:
(1)为父盒子设置border,为外层添加border后父子盒子就不是真正意义上的贴合 (可以设置成透明:border:1px solid transparent)。
(2)为父盒子添加overflow:hidden;
(3)为父盒子设定padding值;
(4)为父盒子添加position:fixed;
(5)为父盒子添加 display:table;
(6)利用伪元素给子元素的前面添加一个空元素
.son:before{ content:"";
overflow:hidden; }