如何清除浮动

作者: 痛心凉 | 来源:发表于2017-10-21 08:43 被阅读18次

    为什么清除CSS浮动这么难?
    因为浮动会使当前标签产生向上浮的效果,同时会影响到前后标签、父级标签的位置及 width height 属性。
    而且同样的代码,在各种浏览器中显示效果也有可能不相同,这样让清除浮动更难了。
    解决浮动引起的问题有多种方法,但有些方法在浏览器兼容性方面还有问题。

    常用的几种清除浮动的方法:

    1,给父元素设置高(height)
    原理:父级div手动定义height,就解决了父级div无法自动获取到高度的问题

    <style type="text/css"> 
       .div1{background:#000080;border:1px solid red;/*解决代码*/height:200px;}
       .div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
       
       .left{float:left;width:20%;height:200px;background:#DDD}
       .right{float:right;width:30%;height:80px;background:#DDD}
       </style> 
    <div class="div1"> 
          <div class="left">Left</div> 
          <div class="right">Right</div> 
    </div>
    <div class="div2">
       div2
      </div>
    

    2、结尾处加空div标签clear:both
    原理:添加一个空div,利用css提高的clear:both清除浮动,让父级div能自动获取到高度

    <style type="text/css"> 
       .div1{background:#000080;border:1px solid red}
       .div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
       
       .left{float:left;width:20%;height:200px;background:#DDD}
       .right{float:right;width:30%;height:80px;background:#DDD}
       
       /*清除浮动代码*/
       .clearfloat{clear:both}
       </style> 
    <div class="div1"> 
            <div class="left">Left</div> 
            <div class="right">Right</div>
            <div class="clearfloat"></div>
       </div>
      <div class="div2">
           div2
      </div>
    

    3、父级div定义overflow:hidden
    原理:必须定义width或zoom:1,同时不能定义height,使用overflow:hidden时,浏览器会自动检查浮动区域的高度

    <style type="text/css"> 
       .div1{background:#000080;border:1px solid red;/*解决代码*/width:98%;overflow:hidden}
       .div2{background:#800080;border:1px solid red;height:100px;margin-top:10px;width:98%}
       
       .left{float:left;width:20%;height:200px;background:#DDD}
       .right{float:right;width:30%;height:80px;background:#DDD}
       </style> 
    <div class="div1"> 
            <div class="left">Left</div> 
            <div class="right">Right</div>
    </div>
    <div class="div2">
       div2
     </div>
    

    4、父级div定义伪类:after和zoom
    原理:IE8以上和非IE浏览器才支持:after,原理和方法2有点类似,zoom(IE转有属性)可解决ie6,ie7浮动问题

    <style type="text/css"> 
       .div1{background:#000080;border:1px soli md red;}
       .div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
       
       .left{float:left;width:20%;height:200px;background:#DDD}
       .right{float:right;width:30%;height:80px;background:#DDD}
       
       /*清除浮动代码*/
       .clearfloat:after{display:block;clear:both;content:"";visibility:hidden;height:0}
       .clearfloat{zoom:1}
       </style> 
    <div class="div1 clearfloat"> 
          <div class="left">Left</div> 
          <div class="right">Right</div> 
    </div>
    <div class="div2">
       div2
    </div>
    

    相关文章

      网友评论

        本文标题:如何清除浮动

        本文链接:https://www.haomeiwen.com/subject/dhabuxtx.html