Skip to content

清除浮动

添加额外标签clear

html
<style>
    * {
        margin: 0;
    }

    .box1 {
        width: 200px;
        height: 200px;
        background-color: green;
        float: left;
    }

    .box2 {
        width: 300px;
        height: 300px;
        background-color: yellow;
    }

    .clear {
        clear: both;
    }
</style>

<body>
    <div class="box1"></div>
    <div class="clear"></div>
    <div class="box2"></div>
</body>

使浮动元素的父级变为BFC块

html
<style>
    * {
        margin: 0;
    }

    .parent {
        overflow: hidden;
    }

    .box1 {
        width: 200px;
        height: 200px;
        background-color: green;
        float: left;
    }

    .box2 {
        width: 300px;
        height: 300px;
        background-color: yellow;
        float: left;
    }
</style>

<body>
    <div class="parent">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>

</body>

使用伪元素:after

css
.parent:after {
    content: "";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}