CSS清除浮动的方法

79 阅读1分钟

当父盒子中有子盒子浮动之后,该子盒子会脱离文档流,导致父盒子高度塌陷。那么如何清除子盒子浮动对父元素的影响呢

html代码:

    <div class="father">
        <div class="first">first</div>
        <div class="second">second</div>
        <div class="third">third</div>
    </div>

css代码:

        .father{
            width: 200px;
            border: 1px solid black;
            padding: 0 20px;
        }
        .first{
            height: 50px;
            border: solid 1px red;
        }
        .second{
            height: 50px;
            border: solid 1px blue;
            float: right;
        }
        .third{
            height: 50px;
            border: 1px solid green;
        }

效果:

1.second盒子的宽度不再是独占一行,而是由内容撑开。但是依然是display: block;

2.second脱离文档流,third盒子占据了second盒子原来的位置。

image.png

1.额外标签法

在浮动元素的后面添加一个块级标签(行内块不行),并给其设置 clear: both;

优点:简单易行,兼容性好,而且无论第几个子盒子浮动都生效

缺点:会产生很多空白标签

    <div class="father">
        <div class="first">first</div>
        <div class="second">second</div>
        <div style="clear: both;"></div>
        <div class="third">third</div>
    </div>

效果:父元素能正确统计自身高度

image.png

2.给浮动元素的父元素设置 overflow: hidden 或 auto;

注意:该方法只适合父元素的最后一个子元素浮动

        .father{
            width: 200px;
            border: 1px solid black;
            padding: 0 20px;

            overflow: auto;
        }
        .first{
            height: 50px;
            border: solid 1px red;
        }
        .second{
            height: 50px;
            border: solid 1px blue;
        }
        .third{
            height: 50px;
            border: 1px solid green;
            float: right;
        }

效果:

image.png

伪元素法

注意:该方法只适合父元素的最后一个子元素浮动

给浮动元素的父元素的伪元素after设置:display: block; clear: both;

        .father{
            width: 200px;
            border: 1px solid black;
            padding: 0 20px;
        }
        .father::after{
            content: '';
            display: block;
            clear: both;
        }
        .first{
            height: 50px;
            border: solid 1px red;
        }
        .second{
            height: 50px;
            border: solid 1px blue;
        }
        .third{
            height: 50px;
            border: 1px solid green;
            float: right;
        }

效果:

image.png