清除浮动

78 阅读1分钟

自己对知识的理解,留作面试用,如有错误请指正

给浮动元素后面的元素设置clear:both

<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>
        .box1{
            width: 50px;
            height: 50px;
            background-color: aqua;
            float: left;
            
        }
    
        .box2{
            width: 150px;
            height: 150px;
            
            clear: both;
            background-color: brown;
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
</body>
</html>

给浮动元素的父元素加伪元素after,display设置为block,加上空标签,clear:both

<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>
        .box::after{
            content: '';
            display: block;
            clear: both;
        }
        .box1{
            width: 50px;
            height: 50px;
            background-color: aqua;
            float: left;
            
        }
    
        .box2{
            width: 150px;
            height: 150px;
            
            /* clear: both; */
            background-color: brown;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="box1"></div>
    </div>
    
    <div class="box2"></div>
</body>
</html>

创建BFC