CSS—嵌套块元素外边距合并导致的塌陷(3种处理方法)

html-css016

CSS—嵌套块元素外边距合并导致的塌陷(3种处理方法),第1张

嵌套块元素外边距合并导致的塌陷(3种处理方法)

一、现象解释

指对于嵌套关系的块元素,若父子双方均有外边距则父元素会塌陷较大的外边距(通俗解释:就是父子均按照最大的外边距进行移动)

tips:谁大塌陷多少

eg:

<style>

.father{

width:500px

height:500px

background-color:rgb(15,213,240)

margin-top:100px

   }

.son{

width:300px

height:300px

background-color:rgb(14,71,226)

margin-top:50px

   }

</style>

<body>

<divclass="father">

<divclass="son">

</div>

</div>

</body>

二、解决方案

1.加一个透明的边框

即:加一个border: 1px solid transparent

<style>

.father{

width:500px

height:500px

background-color:rgb(15,213,240)

margin-top:100px

border:1pxsolidtransparent

   }

.son{

width:300px

height:300px

background-color:rgb(14,71,226)

margin-top:50px

   }

</style>

<body>

<divclass="father">

<divclass="son">

</div>

</div>

</body>

2.给父元素加一个内边距

即:padding:1px

<style>

.father{

width:500px

height:500px

background-color:rgb(15,213,240)

margin-top:100px

padding:1px

   }

.son{

width:300px

height:300px

background-color:rgb(14,71,226)

margin-top:50px

   }

</style>

<body>

<divclass="father">

<divclass="son">

</div>

</div>

</body>

3.给父元素加一个overflow:hidden

4.其他

首先我们先看出现外边距塌陷的三种情况: 1.当上下相邻的两个块级元素相遇,上面的元素有下边距margin-bottom,下面的元素有上边距margin-top,则它们之间的垂直距离取两个值中的较大者。 这时候两个盒子之间的垂直距离不是30px,而是20px。 解决方法: 尽量只给一个盒子添加margin值 2.对于两个嵌套关系的块元素,如果父元素没有上内边距及边框,父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者。 这时候两个盒子会发生合并,上外边距为20px。 解决办法: ①给父元素定义上边框 ②给父元素定义上内边距 ③给父元素添加 overflow:hidden;④添加浮动 ⑤添加绝对定位 3.如果存在一个空的块级元素, border、padding、inline content、height、min-height 都不存在,那么上下边距中间将没有任何阻隔,上下外边距将会合并。 可以理解成中间div宽度为0且上下边距融合,只取margin的最大值。