margin外边距合并问题以及解决方式汇总
简介
块级元素的上外边距和下外边距有时会合并(或折叠)为一个外边距,其大小取其中的最大者,这种行为称为外边距折叠(margin collapsing).
外边距合并的三种情况
1.相邻兄弟姐妹元素
简述:同级别毗邻的两个元素设置了相向的外边距(一个设置margin-top一个设置margin-bottom 另一情况反之)
<style>
.box1 {
width: 200px;
height: 200px;
margin-bottom: 60px;
background: lightblue;
}
.box2 {
width: 200px;
height: 200px;
margin-top: 40px;
background: lightgreen;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
- 解决办法:
- 后者使用position定位;属性fixed或absolute
- 前或后者使用display 属性如下:
- inline-block
- inline-flex
- inline-grid
- inline-table
- table-caption
- 将其中一个元素装入一个开启bfc的元素中如下
<style>
.box1 {
width: 200px;
height: 200px;
margin-bottom: 60px;
background: lightblue;
}
.box2 {
width: 200px;
height: 200px;
margin-top: 40px;
background: lightgreen;
}
.bfc {
overflow: hidden;
}
</style>
<body>
<div class="box1"></div>
<div class="bfc">
<div class="box2"></div>
</div>
</body>
2.父元素和子元素
简述:父元素与其第一个或最后一个子元素之间
如果在父元素与其第一个子元素之间不存在边框、内边距、行内内容,也没有创建块格式化上下文、或者清除浮动将两者的 margin-top 分开;父元素最后一个子元素同上 ,那么这两对外边距之间会产生折叠;此时子元素的外边距会“溢出”到父元素的外面。
<style>
.father {
width: 300px;
height: 300px;
margin-top: 40px;
background: #d425cc;
/* border: 1px solid transparent; */
/* box-sizing: border-box;
padding-top: 40px; */
}
.son {
width: 100px;
height: 100px;
margin-top: 40px;
background: #1eb3f8;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
- 解决办法:
- 给父元素设置边框 border: 1px solid transparent;
- 将父元素的marging-top 改为padding-top 并设置box-sizing
- 子元素使用position定位;属性fixed或absolute
- 前或后者使用display 属性如下:
- inline-block
- inline-flex
- inline-grid
- inline-table
- table-caption
- 在父元素与子元素之间添加元素 但是新增的元素会占据额外的空间 所以不推荐
3.空元素
简述:同级别三个元素中间隔着一个未设置宽高且没有内容的元素 但同时设置了上外边距和下外边距;此时第一个元素与第三个元素之间的距离出现问题,也就是外边距合并产生的问题。
<style>
.box1 {
margin-bottom: 0;
width: 300px;
height: 100px;
background: lightblue;
}
.box2 {
margin-bottom: 50px;
margin-top: 50px;
background: lightgreen;
}
.box3 {
margin-top: 0;
width: 300px;
height: 100px;
background: lightpink;
}
</style>
<body>
<div class="box1">box1距离box2 50px 距离box3 100px</div>
<div class="box2"></div>
<div class="box3">box3距离box2 50px 距离box1 100px</div>
</body>
注意浮动元素和绝对定位元素的外边距不会折叠,如果你觉得折叠了那么一定是遮罩问题。
只有在静态流的元素才会发生外边距合并,故设置 float, position 都可以使得外边距在何种情况都不合并。
水平方向无外边距合并问题出现外边距合并问题的都是垂直方向的。