Hey,吃完饭多陪陪家人吧!

css用clearfix和clear解决float后下一个元素挤上去的问题

   

在进行网页布局时经常使用到float让整个块浮动在某一处,但是使用float后又会出现一个问题:紧接着使用float后的一个块或一个元素会直接挤上去,覆盖上一个块或一个元素。下面给出一个例子:

未使用clearfix或clear

html代码:

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4.     <meta charset="UTF-8"/>
  5.     <title>使用clearfix和clear</title>
  6.     <style type="text/css">
  7.     .test{background:#ccc;height:300px;width:300px;}
  8.     .item1{float:left;background:#f90;height:100px;width:150px;opacity:0.50;}
  9.     .item2{float:right;background:#a90;height:100px;width:150px;opacity:0.50;}
  10.     .item3{background:#000;height:200px;width:150px;}
  11.  
  12.     .clearfix:before,.clearfix:after {content:"";display:table;}
  13.     .clearfix:after {clear:both;overflow:hidden;}
  14.     .clearfix { zoom:1; /* for ie6 & ie7 */}
  15.  
  16.     .clear {clear:both;display:block;font-size:0;height:0;line-height:0;overflow:hidden;}
  17.     </style>
  18. </head>
  19. <body>
  20.     <div class="test">
  21.         <div class="item1"></div>
  22.         <div class="item2"></div>
  23.         <div class="item3"></div>
  24.     </div>
  25. </body>
  26. </html>

效果图:

clearfixandclear1

可见,item3的上半部分已经挤进item1里面了。

 

使用clearfix或clear

html代码:

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4.     <meta charset="UTF-8"/>
  5.     <title>使用clearfix和clear</title>
  6.     <style type="text/css">
  7.     .test{background:#ccc;height:300px;width:300px;}
  8.     .item1{float:left;background:#f90;height:100px;width:150px;opacity:0.50;}
  9.     .item2{float:right;background:#a90;height:100px;width:150px;opacity:0.50;}
  10.     .item3{background:#000;height:200px;width:150px;}
  11.  
  12.     .clearfix:before,.clearfix:after {content:"";display:table;}
  13.     .clearfix:after {clear:both;overflow:hidden;}
  14.     .clearfix { zoom:1; /* for ie6 & ie7 */}
  15.  
  16.     .clear {clear:both;display:block;font-size:0;height:0;line-height:0;overflow:hidden;}
  17.     </style>
  18. </head>
  19. <body>
  20.     <div class="test">
  21.         <div class="item1"></div>
  22.         <div class="item2"></div>
  23.         <div class="clear"></div><!--可将clear改为clearfix-->
  24.         <div class="item3"></div>
  25.     </div>
  26. </body>
  27. </html>

效果图:

clearfixandclear2

 

未经允许不得转载:Rising Sun's Blog » CSS / 前端 » css用clearfix和clear解决float后下一个元素挤上去的问题
标签:
评论 0
 
 
发表评论