清除浮动

需要实现的效果

image-20210331221256966

为什么清除浮动

image-20210331223137663

不清除浮动

image-20210331221119716

 <style>
        div#container {
            border: solid 1px red;
        }

        div div.one {
            height: 200px;
            width: 200px;
            background-color: aquamarine;
            float: left;
        }

        div div.two {
            height: 220px;
            width: 200px;
            background-color: blueviolet;
            float: left;
        }

        div div.three {
            height: 300px;
            width: 200px;
            background-color: brown;

        }
    </style>
</head>

<body>
    <div id="container">
        <div class="one"></div>
        <div class="two"></div>
        <div class="three"></div>
    </div>
</body>

清除浮动

使用 clear:both

clear 值:left(清除左浮动)、right(清除右浮动)、both(清除两侧浮动)

本质就是闭合浮动, 就是让父盒子闭合出口和入口,不让子盒子出来(子元素就算浮动也在父元素内)

 div div.three {
     height: 300px;
     width: 200px;
     background-color: brown;
     clear:both;
 }

最后一个浮动元素前新建标签,在其内部添加 clear:both

缺点:浪费标签

.clearDiv{
    clear:both;
}

使用after伪元素清除浮动

#container:after{
    content:'';/*有内容说明对象存在*/
   	visibility:hidden;/*就算其他操作修改content内容也是不可见的,页面也不会产生混乱*/
    height:0px;/*不需要设置行高*/
    display:block;/*即使是空和隐藏,它也是块元素,是以矩形形式存在*/
    clear:both;
}
#container{
    zoom:1;/*针对的是ie浏览器,因为部分ie不支持伪元素*/
}
posted @ 2021-03-31 22:32  平流层  阅读(57)  评论(0)    收藏  举报