清除浮动的方法

383 阅读1分钟

方法一

使用overflow:hidden;使父盒子形成BFC从而达到清除浮动效果

方法二

给后面的父盒子设置clear:both属性。 clear 表示清除浮动对自己的影响,both 表示左右浮动都清除。

但是此方法存在弊端,因为没有设置高度,所以此盒子的margin属性将失效;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin:0;
            padding:0;

        }
        .box {
            clear:both;
            /* 此时margin属性已经失效,所以不会有任何效果 */
            margin-top:10px;
        }
        p {
            float:left;
            width:100px;
            height:100px;
            background-color:orange;
            margin-right:10px;
        }
    </style>
</head>
<body>
    <div>
        <p></p>
        <p></p>
    </div>
    <div class="box">
        <p></p>
        <p></p>
    </div>
</body>
</html>

方法三

使用::after伪元素给盒子**添加最后一个子元素必须添加content="";并且给::after 设置 clear:both;并且需要转为块级元素 display:block;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin:0;
            padding:0;
        }
        .clearfix::after {
            content:"";
            clear:both;
            /* 必须转为块级元素才能实现相应效果 */
            display:block;
        }
        div {
            margin-bottom:10px;
        }
          p {
            float:left;
            width:100px;
            height:100px;
            background-color:orange;
            margin-right:10px;
        }
    </style>
</head>
<body>
    <div class="clearfix">
        <p></p>
        <p></p>
    </div>
    <div class="clearfix">
        <p></p>
        <p></p>
    </div>
</body>
</htm

方法四

在两个父盒子之间”隔墙“,隔一个携带clear:both;的盒子

 .c1 {
            /* 设置完成之后墙上下两个盒子的margin属性将失效 */
            clear:both;
          
        }

通过对这隔墙进行设置height用这隔墙的高度充当间隔。

  /* 设置墙的高度 */
        .h20 {
            height:10px;
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin:0;
            padding:0;
        }
        p {
            float:left;
            width:100px;
            height:100px;
            background-color:orange;
            margin-right:10px;
        }
        .c1 {
            /* 设置完成之后墙上下两个盒子的margin属性将失效 */
            clear:both;
          
        }
        /* 设置墙的高度 */
        .h20 {
            height:10px;
        }
    </style>
</head>
<body>
    <div>
        <p></p>
        <p></p>
    </div>
    <!-- 添加一堵墙 -->
    <div class="c1 h20"></div>
    <div>
        <p></p>
        <p></p>
    </div>
</body>
</html>