先来看例子:


什么叫浮动呢?
浮动其实是指元素从网页的正常流动中移除,即脱离文档流。选择将元素在其容器的左侧或右侧放置其实就是指元素在脱离文档流之后,元素一直向最左边或者右边靠拢,直至碰到父元素或者另一个浮动元素。
我们为什么要清除浮动呢?
大家请看图一,在父盒子未设置高度时,子盒子又设置了浮动,导致父盒子高度塌陷,因为父盒子在计算高度时并未将浮动的子盒子算入。
所以我们要避免这种情况,也就是清除浮动,使得结果如同图二或者图三。
那我们要如何清除浮动呢?
额外标签法(不是很推荐)
这种方法见如下代码
其实就是在父盒子的浮动子盒子之后加入一个额外的块级盒子,为其设置属性clear:both
clear:both的意思可以参考这个博客,讲的很好,尤其对于clear的其他属性值也做了讲解,大家可以去看看:
(43条消息) 理解CSS clear:both/left/right的含义以及应用_Wendy-CSDN博客_clear:both的含义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <style> span{ width: 200px; height: 200px; background-color: pink; float:left; margin:10px; } div{ border: powderblue 2px solid; } </style> <body> <div id="one"> <span></span> <span></span> <div style="clear: both"></div> </div> </body>
|
after伪元素清除浮动(推荐)
这种方法呢,是比较推荐大家使用的,因为它是利用伪元素产生的盒子
代码如下,就是为父盒子的after中添加如下属性,其中不可省略的属性是content:""、display:block、clear:both
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> span{ width: 200px; height: 200px; background-color: pink; float:left; margin:10px; } div{ border: powderblue 2px solid; }
div::after{ content: ""; display: block; height: 0; background-color: salmon; clear:both; visibility: hidden; }
</style> </head> <body> <div> <span></span> <span></span> </div> </body> </html>
|
- 为父级元素添加双伪元素(推荐)
其实这种方法跟第二种比较类似,都是添加伪元素来清除浮动,不同的地方就是属性值不同,即:
before和after都需添加display:table,且after需要添加clear:both
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> span{ width: 200px; height: 200px; background-color: pink; float:left; margin:10px; } div{ border: powderblue 2px solid; } #two::before,#two::after{ content:""; display: table; } #two::after{ clear:both }
</style> </head> <body> <div id="two"> <span></span> <span></span> </div> </body> </html>
|
BFC Block Formatting Contexts 块级格式化上下文
BFC的特点之一就是计算高度的时候会把内部浮动元素的高度也计算在内,所以能够实现BFC的就能够实现清除浮动,比如:
1 2
| 1. overflow:auto;(除了visible都可以) 2. display:inline-block;
|
BFC的触发条件
- 根元素HTML
- 浮动元素 float: left | float: right
- 定位元素 position: absolute | position: fixed
- display 值为 inline-block、table-cell、table-caption、table、inline-table、flex、inline-flex、- - grid、inline-grid
- overflow 除了visible的其他值都可以,hidden、scroll、auto