css清除浮动

2017-08-25  本文已影响7人  xilong

经常会遇到需要清除浮动的情况,总结了以下4种情况,以及各自的优缺点。

1、给父元素设置高度
这是一种最容易想到的方法,前提是需要知道子元素需要占用的高度(一般比较局限)

2、给父元素设置overflow:hidden 或者 overflow:auto
这个方法其实不好用,因为当你有元素需要 超出父元素的时候就不行了(曾经尝试用绝对定位超出父元素,结果都不行)

    <div class="outer">
        <div class="inner"></div>
        <div class="inner"></div>
    </div>
css  
   .outer{
        width: 200px;
        background-color: #04b4ba;
        overflow: auto;          /*或者  overflow: hidden;*/
    }
    .inner{
        width: 50px;
        height: 50px;
        background-color: red;
        float: left;
    }

3、采用clear: both;(需要额外增加一个子元素)

    <div class="outer">
        <div class="inner"></div>
        <div class="inner"></div>
       <div class="clear"></div>
    </div>
css  
   .outer{
        width: 200px;
        background-color: #04b4ba;
      }
    .inner{
        width: 50px;
        height: 50px;
        background-color: red;
        float: left;
    }
  .clear{
        clear: both;
    }

4、采用:after 伪元素法(基本上是一种最好的方法了)

    <div class="outer clearfix">
        <div class="inner"></div>
        <div class="inner"></div>
      </div>
css  
   .outer{
        width: 200px;
        background-color: #04b4ba;
        }
    .inner{
        width: 50px;
        height: 50px;
        background-color: red;
        float: left;
    }
      .clearfix:after{
        content: '';
        display: block;
        clear: both;
        height: 0;
        visibility: hidden;
    }
    .clearfix{
        zoom: 1;   /*兼容 IE*/
    }

参考文章 https://segmentfault.com/a/1190000003937063

上一篇 下一篇

猜你喜欢

热点阅读