margin塌陷
- 先举个例子
<style>
.wrapper{
width:200px;
height:200px;
background-color:red;
margin-top:100px;
}
.box{
width:50px;
height:50px;
background-color:#eee;
opacity:0.8;
margin-top: 100px;
}
</style>
</head>
<body >
<div class="wrapper">
<div class="box"></div>
</div>
<body>
效果如下:
距离上边100px,现在给里面的小方块设置margin-top:100px;发现两个方块位置没动;
而当给里面的小方块设置margin-top:150px;小方块带着大方块往下移动了50px
- 原理:父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margi会取其中最大的值。
- 正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位。
但由于margin的塌陷,父级相对浏览器定位。而子级没有相对父级定位,子级相对父级,就像坍塌了一样。
margin塌陷解决方法
- 给父级设置边框或者内边距
- 不建议使用,会增加px
.wrapper{
width:200px;
height:200px;
background-color:red;
margin-top:100px;
border-top: 1px solid red;
/* padding-top: 1px; */
}
效果如下:
2. 触发bfc(块级格式上下文),改变父级的渲染规则
- 方法:
改变父级的渲染规则有以下四种方法,给父级盒子添加
①position:absolute/fixed
②display:inline-block;
③float:left/right
④overflow:hidden
- 这四种方法都能触发bfc,但是使用的时候都会带来不同的麻烦,具体还需根据具体情况选择没有影响的方法,来解决margin塌陷。
margin合并
- 原因:两个兄弟结构的元素在垂直方向上的margin是合并的
- 代码如下
<style>
* {
padding: 0;
margin: 0;
}
.box{
height: 30px;
margin-bottom: 100px;
background-color: red;
}
.box1 {
height: 30px;
margin-top: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box1"></div>
</body>
效果如下:
box和box1中间只有100px
- margin合并问题也可以使用bfc(块级格式化上下文)解决
- 给box1加上一层父级元素并加上overflow:hidden;
<div class="wrapper">
<div class="box1"></div>
</div>
.wrapper{
overflow:hidden;
}
- 给两个盒子都加一层父级再加bfc
<div class="wrapper">
<div class="box"></div>
</div>
<div class="wrapper">
<div class="box1"></div>
</div>
-
虽然可以解决问题,但是这两种方法都改变了HTML结构,在开发中是不能采用的。
-
所以在实际应用时,在margin合并这个问题上,我们一般不用bfc,而是通过只设置上面的元素的margin-bottom来解决距离的问题。