Loading... 清除浮动的方法 -------------- 方法一:添加新的元素 、应用 clear:both; 在浮动的盒子之下再放一个标签,在这个标签中使用clear:both,来清除浮动对页面的影响. 注意:一般情况下不会使用这一种方式来清除浮动。因为这种清除浮动的方式会增加页面的标签,造成结构的混乱. ```css .clear{ clear: both; } <div class="box"> <div class="red">1</div> <div class="sienna">2</div> <div class="blue">3</div> <div class="clear"></div> </div> ``` 方法二:父级div定义 overflow: auto(注意:是父级div也就是这里的 div.outer) 原理:使用overflow属性来清除浮动有一点需要注意,overflow属性共有三个属性值:hidden,auto,visible。我们可以使用hiddent和auto值来清除浮动,但切记不能使用visible值。 ```css .over-flow { overflow: auto; zoom: 1; } /*zoom1; 是在处理兼容性问题*/ <body> <div class="box over-flow"> <div class="red">1</div> <div class="sienna">2</div> <div class="blue">3</div> </div> </body> ``` 方法三: 使用伪元素来清除浮动(:after,注意:作用于浮动元素的父亲) 主要推荐使用这种方法清除浮动 ```css .clearfix:after{ content:"";/*设置内容为空*/ height:0;/*高度为0*/ line-height:0;/*行高为0*/ display:block;/*将文本转为块级元素*/ visibility:hidden;/*将元素隐藏*/ clear:both;/*清除浮动*/ } .clearfix{ zoom:1;/*为了兼容IE*/ } <div class="box clearfix"> <div class="red">1</div> <div class="sienna">2</div> <div class="blue">3</div> </div> ``` 方法四:使用双伪元素清除浮动 ```css .clearfix:before,.clearfix:after { content: ""; display: block; clear: both; } .clearfix { zoom: 1; } ``` Last modification:September 4, 2023 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏