当父盒子和子盒子都同时拥有margin-top时,都会使嵌套块元素塌陷
<style> .father { width: 400px; height:400px; margin-top:50px; background-color:black; } .son{ width:200px; height:200px; background-color:red; margin-top:100px; } </style> <div class="father"> <div class="son"> </div> </div>此时父盒子的上边距会变成100px,而子盒子相对于父盒子没有上边距 解决方法:
为父元素定义上边框。为父元素定义上内边距为父元素添加overflow:hidden。 <style> .father { width: 400px; height:400px; margin-top:50px; background-color:black; /*border-top:1px solid transpanrent;*/ /*padding-top:1px;*/ overflow:hidden; } .son{ width:200px; height:200px; background-color:red; margin-top:100px; } </style> <div class="father"> <div class="son"> </div> </div>添加的标签必须是块级元素
<style> .box{ width:500px; border:1px solid blue; } .one { width:200px; height:200px; float:left; background-color:red; } .clear { clear:both; } .footer { height:200px; background-color:black; } </style> <div class="box"> <div class="one"></div> <div class="one"><div/> <div class="clear"></div> </div> <div class="footer"></div>缺点:溢出部分会隐藏
<style> .box{ width:500px; border:1px solid blue; overflow:hidden; } .one { width:200px; height:200px; float:left; background-color:red; } .footer { height:200px; background-color:black; } </style> <div class="box"> <div class="one"></div> <div class="one"><div/> </div> <div class="footer"></div>以上是自己学习过程中总结出来的,有什么问题欢迎指正。