css:垂直方向外边距margin塌陷问题及解决

简介: css:垂直方向外边距margin塌陷问题及解决

margin塌陷现象:


在垂直方向如果有两个元素的外边距有相遇,在浏览器中加载的真正的外边距不是两个间距的加和,而是两个边距中值比较大的,边距小的塌陷到了边距值大的值内部。


统一用到的的样式


* {
  margin: 0;
  padding: 0;
}
.box {
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

一、水平方向margin不会塌陷

横向排列(水平方向)边距不会被合并


<style type="text/css">
.box-8 {
  margin-right: 10px;
  background-color: green;
}
.box-9 {
  margin-left: 20px;
  background-color: gray;
}
</style>
<div style="display: flex;">
  <div class="box box-8">box-8</div>
  <div class="box box-9">box-9</div>
</div>

image.png

二、垂直方向margin出现塌陷

1、上下外边距合并


<style type="text/css">
.box-1 {
  /*底部margin 10px被box-2合并了*/
  margin-bottom: 10px;
  background-color: green;
}
.box-2 {
  margin-top: 20px;
  background-color: gray;
}
</style>
<div class="box box-1">box-1</div>
<div class="box box-2">box-2</div>

两个垂直元素的margin取了最大值20px

image.png

2、内外边距合并

<style type="text/css">
.box-3 {
  margin-top: 10px;
  background-color: green;
}
.box-4 {
  margin-top: 20px;
  width: 50px;
  height: 50px;
  line-height: 50px;
  background-color: gray;
}
</style>
<div class="box box-3">
  <div class="box box-4">box-4</div>
</div>

上边距只保留了20px

image.png

3、多个子元素内外边距合并


<style type="text/css">
.box-5 {
  background-color: green;
}
.box-6 {
  margin-top: 10px;
  background-color: blue;
}
.box-7 {
  margin-top: 20px;
  width: 80px;
  height: 80px;
  line-height: 80px;
  background-color: gray;
}
</style>
<div class="box box-5">
  <div class="box-6"></div>
  <div class="box box-7">box-7</div>
</div>

box-6和box-7只保留了两者中最大值20px

image.png


三、垂直方向margin塌陷解决方法

1、同级元素: 只设置一个元素的margin


<style type="text/css">
.box-10 {
  background-color: green;
}
.box-11 {
  margin-top: 30px;
  background-color: gray;
}
</style>
<div class="box box-10">box-10</div>
<div class="box box-11">box-11</div>

两个垂直元素上下边距和有了30px

image.png


2、父子元素: 子元素不设置margin,父元素设置padding


<style type="text/css">
.box-12 {
  margin-top: 10px;
  background-color: green;
  padding-top: 20px;
}
.box-13 {
  /* margin-top: 20px; */
  width: 50px;
  height: 50px;
  line-height: 50px;
  background-color: gray;
}
</style>
<div class="box box-12">
  <div class="box box-13">box-13</div>
</div>

外层上边距10px,内层上边距有20px,没有被合并

image.png


参考


margin塌陷问题及解决

CSS外边距合并(塌陷/margin越界)

CSS margin塌陷问题及解决方案

相关文章
|
5月前
|
前端开发
CSS 什么是外边距重叠?重叠的结果是什么?
CSS 什么是外边距重叠?重叠的结果是什么?
|
1月前
|
前端开发
CSS外边距重叠:原理、结果
CSS外边距重叠:原理、结果
19 0
|
3月前
|
前端开发 容器
css 中可以让文字在垂直和水平方向上重叠的两个属性是什么?
css 中可以让文字在垂直和水平方向上重叠的两个属性是什么?
|
3月前
|
前端开发
CSS外边距重叠:原理、结果
CSS外边距重叠:原理、结果
15 1
|
3月前
|
人工智能 前端开发 开发者
Baidu千帆大模型赋能——CSS控制DIV垂直水平居中——送给大一的孩子们,学会用AI思维来帮助你解决问题
Baidu千帆大模型赋能——CSS控制DIV垂直水平居中——送给大一的孩子们,学会用AI思维来帮助你解决问题
27 1
|
5月前
|
前端开发
CSS外边距重叠:原理、结果
CSS外边距重叠:原理、结果
|
5月前
|
前端开发
css如何将border线加到元素内部,占内边距,不占外边距
css如何将border线加到元素内部,占内边距,不占外边距
54 0
|
7月前
|
前端开发
css如何让实现一个元素在网页中垂直水平居中
css如何让实现一个元素在网页中垂直水平居中
25 0
|
7月前
|
前端开发 容器
|
7月前
|
前端开发 容器
Web前端 — CSS之盒模型 以及margin负值、塌陷重叠问题
Web前端 — CSS之盒模型 以及margin负值、塌陷重叠问题
31 0