margin坍塌和margin合并
margin坍塌
嵌套的父子元素,分别给父元素设置上边距100px,子元素也设置一个上边距50px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin塌陷</title>
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(231, 73, 107);
margin-left: 100px;
margin-top: 100px;
}
.son{
width: 100px;
height: 100px;
background-color: rgb(43, 236, 194);
margin-left: 50px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果如下
结果我们出乎意料会发现,水平方向的距离确实没问题,但是垂直方向上,明明子元素设置了margin-top距离顶部50px,按道理它会距离父元素顶部50px才对。事实上,这是一个bug。大家都叫它margin塌陷。很多人可能都不太理解,为什么叫它塌陷,其实可以深入理解理解,如上述例子,原本子元素要距离父元素顶部50px,现在没有动,也就是父元素的顶棚对子元素来说没有作用,相当于没有,相当于塌陷了。所以叫margin塌陷。
一句话总结:父子嵌套的元素垂直方向的margin取最大值。
但是有时候我们不希望有这样的问题,那我们如何解决margin坍塌的问题呢 可以通过触发BFC来解决,下面通过overflow:hidden触发bfc,即可
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(231, 73, 107);
margin-left: 100px;
margin-top: 100px;
overflow: hidden;/* 触发bfc */
}
.son{
width: 100px;
height: 100px;
background-color: rgb(43, 236, 194);
margin-left: 50px;
margin-top: 50px;
}
</style>
margin合并
把两个兄弟块元素,一个设置下边距100px,一个设置上边距100px,让两个元素相聚200px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin合并</title>
<style>
.one{
background-color: pink;
height: 20px;
margin-bottom: 100px;
}
.two{
background-color: purple;
height: 20px;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
</html>
我们发现两个元素之间,他们的margin-bottom和margin-top合并了,并显示的是较大的值
同样我们可以用bfc解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin合并</title>
<style>
.one {
background-color: pink;
height: 20px;
margin-bottom: 100px;
}
.two {
background-color: purple;
height: 20px;
margin-top: 100px;
}
.wrap{
/* 触发bfc */
overflow: hidden;
}
</style>
</head>
<body>
<!-- 这里有更改结构哦 -->
<div class="one"></div>
<div class="wrap">
<div class="two"></div>
</div>
</body>
</html>
解决问题,但是我们一般不这么解决,因为margin合并和margin坍塌不一样,margin坍塌只添加了css,margin合并除了添加css,还修改了html结构,我们知道一般html是不能乱改动的,所以通过数学计算解决这个margin合并的问题,我们只需要设置前面的元素margin-bottom:200px,或者设置后面的元素margin-top:200px即可。
BFC
BFC是块级格式化上下文,他是一个独立的渲染区域,其中的元素布局不受外界的影响
如何触发BFC
- float属性不为none
- position为absolute或fixed
- display:inline-block,table-cell,table-caption,flex,inline-flex
- overflow不是visible
BFC可以做什么
- 利用BFC可以避免外边距折叠