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

html-css023

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.加一个空div标签清除浮动(缺点:不利于优化,优点:兼容性强)<div style="clear:both"></div>

2. overflow+zoom(优点:兼容性强。 缺点:对margin属性有影响,不能设负值,设负值无效。负值绝对定位也不可以。)

example { overflow:hiddenzoom:1}

3.after+zoom (最好用的,最推荐的,兼容性也很好)

example{zoom:1}

example:after{ display:blockcontent:'', clear:bothheight:0overflow:hidden}

4.让父元素本身也浮动(不推荐,如果也设置浮动,父元素宽度就会随着子元素变化)