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

html-css014

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.其他

解决办法:

第一种:可以在父盒子设置边框,在.father{}里边加边框 类似border:1px solid green此时margin将会相对于父盒子进行定位。

第二种:在父盒子设置overflow为hidden,即在.father{}里边加一句 overflow:hidden

第三种:可以在父盒子设置padding