CSS清除浮动的四种方式

113 阅读1分钟

实现如图布局

在这里插入图片描述

当给黄蓝两个盒子设置浮动后导致高度塌陷,如下图。

在这里插入图片描述

源代码

<body>
    <div class="container">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>
    <div class="box"></div>
</body>
.box1,.box2 {
            width: 200px;
            height: 200px;
            float: left;
        }
        .box1 {
            background-color: yellow;
        }
        
        .box2 {
            background-color: blue;
        }
        .box {
            width: 300px;
            height: 300px;
            background-color: green;
        }

清除浮动的方法

方法一

给浮动的两个盒子的父盒子设置固定高度

.container {
           height: 200px;
        }

方法二

清浮动——给浮动的盒子下方的盒子设置clear:left;

  .box {
            width: 300px;
            height: 300px;
            background-color: green;
            clear: left;
        }

注:clear:leftfloat:left向对应

方法三

在浮动元素后面补一个盒子

<div class="container">
        <div class="box1"></div>
        <div class="box2"></div>
        <div style="clear: left;"></div> 
    </div>

方法四

给浮动元素的父盒子加overflow: hidden;

  .container {
           overflow: hidden; 
        }

欢迎关注

掘金:juejin.cn/user/415657…

Github:github.com/zhubingran

CSDN:blog.csdn.net/qq_43118757

QQ:1330022055