天天看点

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>
           
css:垂直方向外边距margin塌陷问题及解决

二、垂直方向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

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

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

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

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

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

三、垂直方向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

css:垂直方向外边距margin塌陷问题及解决
<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>

           
  1. margin塌陷问题及解决
  2. CSS外边距合并(塌陷/margin越界)
  3. CSS margin塌陷问题及解决方案
css