外边距塌陷也称为外边距合并,是指两个在正常流中相邻(兄弟或父子关系)的块级元素的外边距,组合在一起变成单个外边距,不过只有上下外边距才会有塌陷,左右外边距不会出现这种问题。(行内元素、浮动元素或绝对定位之间的外边距不会合并。)
1.父子关系()
- 如果父元素在子元素的margin的同向上有padding或border的话,子元素的margin相对于父元素,`*否则相对于父元素以外的元素`*
<div class="father1"> <div class="son1">子元素1</div> </div>
.father1{ width: 200px; height: 200px; background-color: yellow; } .son1{ width: 150px; height: 150px; text-align: center; line-height: 150px; background-color: deepskyblue; }
1.1.给子元素添加margin-top
.son1{ width: 150px; height: 150px; text-align: center; line-height: 150px; background-color: deepskyblue; margin-top: 50px; }
1.2注释掉子元素的margin-top,给父元素添加margin-top
.father1{ width: 200px; height: 200px; background-color: yellow; margin-top: 50px; }
1.3给父元素和子元素都添加margin-top,且大小不一样
.father1{ width: 200px; height: 200px; background-color: yellow; margin-top: 50px; } .son1{ width: 150px; height: 150px; text-align: center; line-height: 150px; background-color: deepskyblue; margin-top: 100px; }
2:相邻兄弟关系(上下相邻 左右不会出现外边距塌陷)
<div class="father1"></div> <div class="father2"></div>
.father1{ width: 100px; height: 100px; background-color: yellow; } .father2{ width: 100px; height: 100px; background-color: pink; }
.father1{ width: 100px; height: 100px; background-color: yellow; //加上margin margin-bottom: 100px; } .father2{ width: 100px; height: 100px; background-color: pink; //加上margin margin-top: 50px; }
3.当外边距塌陷时,外边距之间的计算方式是怎样的?
3.1两个都是正数,取较大的值
3.2两个都是负数,取绝对值较大的值
3.3一正一负,取两个值得和
4.解决外边距塌陷的方法
第一种:给父元素增加内边距padding值
第二种方式:父元素增加边框border值
第三种方式:父元素增加overflow:hidden
第四种方式:给父元素或者子元素增加浮动,让其脱离标准流都可以
第五种:将父元素转变为行内块元素,display:inline-block
第六种:给父元素或者子元素定位都可以,原理同样是使其脱离标准流,不过只能用绝对定位和固定定位
第七种:给父盒子增加flex或者inline-flex