如何清除浮动?

一:我们在使用浮动时,不可避免的会遇到高度塌陷的问题。
因为常规流盒子在计算高度时,不考虑浮动盒子。
举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .box{
            width: 100px;
            height: 100px;
        }
        .one{
            background-color: red;
        }
        .two{ 
            background-color: blue;
        }
        .three{
            background-color: green;
        }
        .four{
            background-color: yellow;
        }
        /* 浮动 */
        .fl{
            float: left;
        }
    </style>
</head>
<body>
    <div class="content clearfix">
        <div class="box one fl"></div>
        <div class="box two fl"></div>
        <div class="box three fl"></div>
        <div class="box four fl"></div>
    </div>
    <p>hello world!</p>
</body>
</html>

效果图为
在这里插入图片描述
按照常规流来看,hello world应该在盒子的下方,但是现在却跟着盒子后面。影响了我们原本的目的(让盒子横向排列,不包括其它元素)。所以我们要清除浮动带来的影响。

二:清除浮动办法。

  1. clear:left/right/both;
  2. 父元素设置overflow的值为visible;
  3. 给父元素添加一个伪类。

建议使用使用第三种方法:主要问题是有的浏览器不支持(IE)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .box{
            width: 100px;
            height: 100px;
        }
        .one{
            background-color: red;
        }
        .two{ 
            background-color: blue;
        }
        .three{
            background-color: green;
        }
        .four{
            background-color: yellow;
        }
        /* 浮动 */
        .fl{
            float: left;
        }
        /* 清除浮动 */
        .clearfix::after{
            content: " ";
            display: block;
            clear: both;
        }
    </style>
</head>
<body>
    <div class="content clearfix">
        <div class="box one fl"></div>
        <div class="box two fl"></div>
        <div class="box three fl"></div>
        <div class="box four fl"></div>
    </div>
    <p>hello world!</p>
</body>
</html>

效果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值