外边距塌陷也称为外边距合并,是指两个在正常流中相邻(兄弟或父子关系)的块级元素的外边距,组合在一起变成单个外边距,不过只有上下外边距才会有塌陷,左右外边距不会出现这种问题。
第一种:父子关系
<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; }复制代码
给子元素添加margin-top
.son1{ width: 150px; height: 150px; text-align: center; line-height: 150px; background-color: deepskyblue; margin-top: 50px; }复制代码
注释掉子元素的margin-top,给父元素添加margin-top
.father1{ width: 200px; height: 200px; background-color: yellow; margin-top: 50px; }复制代码
给父元素和子元素都添加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; }复制代码
第二种:相邻兄弟关系
<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-bottom: 100px; } .father2{ width: 100px; height: 100px; background-color: pink; margin-top: 50px; }复制代码
当外边距塌陷时,外边距之间的计算方式是怎样的? 1.两个都是正数,取较大的值 2.两个都是负数,取绝对值较大的值 3.一正一负,取两个值得和