清除浮动的四种方法

125 阅读1分钟
  • 清除浮动的四种方法

    1. Overflow:hidden;(用作于父级)
    2. 给浮动的父级设置一个高度
    3. clear:both;
    4. 使用伪类 ::after
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            border: 2px solid red;
            /* overflow: hidden; */
            /* height: 100px; */
            width: 200px;
        }
        .box::after{
            content: '';
            display: block;
            clear: both;
        }
        .a,.b{
            float:left;
            width: 100px;
            height: 100px;
        }
        .a{background-color: green;}
        .b{background-color: blue;}
        div{margin:10px;}
    </style>
</head>
<body>
    <div class="box">
        <div class="a"></div>
        <div class="b"></div>
        <!-- <div class="a"></div>
        <div class="b"></div>
        <div class="a"></div>
        <div class="b"></div> -->
        <!-- <div style="clear: both;"></div> -->
    </div>
</body>
</html>