子div设置浮动无法把父div撑开

2016/12/26 8:41:43   阅读:1735    发布者:1735

<div class="mainBox"> 
  <div class="leftBox"></div> 
    <div class="rightBox"></div> 
    <div class="clear"></div> 
</div> 

 

注意:leftBox和rightBox设置浮动之后脱离了普通的文档流,不再占用原来文档中的位置,
因此无法把父div撑开。

解决的方法:

①可以给父div也设置高度为300px,使页面中的leftBox和rightBox看起来"好像"还在原来的位置; 
②定义一个类选择器,并设置clear:both;清除浮动,同时为了解决IE6中div
有高度的问题可以增加属性height:0;overflow:hidden;
.mainBox 
{ 
    width:960px; 
    margin:0 auto; 
    background-color:#CFF; 
    overflow:visible; 
} 
.leftBox 
{ 
    width:740px; 
    height:300px; 
    background-color:#C9F; 
    float:left; 
} 
.rightBox 
{ 
    width:210px; 
    height:300px; 
    background-color:#FCF; 
    float:right; 
} 
.clear 
{ 
    clear:both; 
    height:0;/*解决IE6下有高度的问题*/ 
    overflow:hidden; 
} 

  

/*父元素不设置高度,子元素是有高度的,会把父元素撑开*/ 

/*如果子元素设置浮动的话,就脱离了文档流,就不会把父元素撑开了*/ 

/*因此,子元素设置浮动,父元素需要设置高度*/