Loading

清除浮动的方法

情景:给脱标(使用了浮动或者定位)的元素增加了一个父级元素,但是又不方便给高度的情况下
(父盒子给高度也是一个解决方法,但是大多数情况下,因为盒子的内容会经常改变,父盒子高度固定,需要每次去调整)
<body>
    <div class='box'>
        <div class="red"></div>
        <div class="blue"></div>
    </div>
    <div class="box1"></div>
</body>
<style type="text/css">
        .box{
            width: 800px;
            background: rgb(17, 12, 12);
        }
        .red{
            background:red;
            width: 200px;
            height: 200px;
            float: left;
        }
        .blue{
            background: blue;
            width: 200px;
            height: 200px;
            float: left;
        }
        .box1{
            background: rgb(154, 184, 24);
            width: 300px;
            height: 300px;
        }
    </style>

问题:父级元素高度为零导致影响下面盒子的布局,如上图所示,box1跑到红盒子和绿盒子的下面去了
解决办法:
  • 盒子内容固定的情况:给父盒子设置高度
 .box {
            height: 200px;
        }

  • 盒子内容不固定,需要随内容的改变而改变,就需要清除浮动,有下面这4种方法:

  1.第一种方法,在最后一个浮动的标签后面增加一个盒子并设置clear:both

<body>
    <div>
        <div class="red"></div>
        <div class="blue"></div>
        <div class="addbox"></div>
    </div>
    <div class="box1"></div>
</body>
.addbox{
            width: 100px;
            clear: both;
        }

  2.第二种方法:父级盒子设置overflow:hidden;触发bfc

.box{
            overflow: hidden;
        }

  3.第三种单伪元素标签法,需要给父盒子一个类名clearfix

.clearfix:after{
            content: "";
            height: 0;
            overflow: hidden;
            visibility: hidden;
            display: block;
            clear: both;
        } 
.clearfix {
            zoom: 1;/*兼容IE*/
        }
<body>
    <div class="box clearfix">
        <div class="red"></div>
        <div class="blue"></div>
    </div>
    <div class="box1"></div>
</body>

  4.第四种双伪元素标签法,需要给父盒子一个类名clearfix

.clearfix :before,.clearfix:after{
            content: "";
            display: table;
        }
.clearfix:after{
            clear: both;
        } 
.clearfix {
            zoom: 1;/*兼容IE*/
        }
<body>
    <div class="box clearfix">
        <div class="red"></div>
        <div class="blue"></div>
    </div>
    <div class="box1"></div>
</body>

posted @ 2018-04-08 16:49  澎湃_L  阅读(270)  评论(0编辑  收藏  举报