CSS清除浮动的五种方法(超详细)

1.为什么要清除浮动?

浮动的原理是让图片脱离文档流,直接浮在桌面上。我们一般布局的时候都是只设置宽度不设置高度,让内容来自动填充高度。但使用浮动后会让原本填充的高度消失,父元素高度为0,后续添加内容布局会产生混乱,造成高度塌陷,这时候就可以利用清除浮动来解决父元素高度塌陷的问题。

  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .box1{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
    .box2{
      width: 80px;
      height: 80px;
      background-color: skyblue;
    }
  </style>


   <div class="box1">1</div>
   <div class="box2">2</div>

以上面的代码为例,默认状态下,它的展示效果是这样的:

现在给1号盒子添加一个左浮动float :left,我们来看看会发生什么:

 我们可以看到2号盒子在桌面上不见了,那么原因是什么呢,原因是1号盒子漂浮起来了,原本所占的空间空缺出来了,所以2号盒子到了1号盒子的下方,如图所示,

 那么下面是我们的解决方法:

2.解决方法一(clear)

直接给第二个盒子添加一个clear:left  这里需要注意,clear消除的是上一个盒子对自己的影响,所以,前面一个盒子往哪边浮动,我们就clear哪边,这里的上一个盒子是float:left,所以我们在第二个盒子上添加的也是clear:left

 3.解决方法二(overflow:hidden)

overflow这个属性需要添加在父元素上,所以我们给两个盒子添加一个父元素,为了看清楚高度塌陷,我们在添加一个底部盒子,如下:

 <style>
    *{
      margin: 0;
      padding: 0;
    }
    .box1{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
    .box2{
      width: 80px;
      height: 80px;
      background-color: skyblue;
    }
    .father{
      width: 100%;
      border: 2px solid red;
    }
    .bottom{
      width: 100%;
      height: 200px;
      background-color: green;
    }
  </style>


    <div class="father">
      <div class="box1">1</div>
      <div class="box2">2</div>
    </div>
    <div class="bottom">3</div>

这是默认状态下的状况 

 现在给1号盒子和2号盒子添加浮动,我们来看看会发生什么

<style>
  .box1{
      width: 100px;
      height: 100px;
      background-color: pink;
      float: left;
    }
    .box2{
      width: 80px;
      height: 80px;
      background-color: skyblue;
      float: left;
    }
</style>

可以看到我们的底部盒子不在原来的位置了,原因是什么呢,原因就是此时父元素我们并没有给他设置高度,父元素的高度完全是1号2号盒子撑起来的,现在给1号2号盒子添加了浮动,不占据原来的位置了,所以父元素此时的高度为零,不占位置了,底部盒子就会上去,造成高度塌陷.

解决方法就是:给父元素添加一个overflow:hidden

<style>
   .father{
      width: 100%;
      border: 2px solid red;
      overflow: hidden;
    }
</style>

 4.解决方法三(给父元素添加高度)

第三种方法就是给父元素添加一个高度,注意,父元素高度的设置一定要大于子元素中高度最高的盒子,以此例子来说就是,子元素中最高的盒子高度是100px,那么父元素的高度一定要大于等于100px

<style>
    .father{
      width: 100%;
      height: 100px;
      border: 2px solid red;
    }
</style>

 5.解决方法四(额外标签法)

在需要清除浮动的标签后面添加一个空标签,给其加上clear:both

    <div class="father">
      <div class="box1">1</div>
      <div class="box2">2</div>
      <div class="clear"></div>
    </div>
    <div class="bottom">3</div>
<script>
   .clear{
      clear: both;
    }
</script>

6.解决方法五(使用after伪元素清除浮动

这个方法也有一个缺点,就是不支持IE6,IE7

<style>
  .father:after{
    content: "";
    display: block;
    height: 0;
    clear:both;
    visibility: hidden;
}
.father{
    zoom: 1;
   /*IE6清除浮动的方式 只有IE6-IE7执行,其他浏览器不执行*/
}

</style>

猜你喜欢

转载自blog.csdn.net/weixin_48649246/article/details/127999792