BFC的理解
块级格式化上下文,它是指一个独立的块级渲染区域,只有Block-level Box参于,该区域拥有一套渲染规则来约束块级盒子的布局,且与区域外部无关。
BFC现象
- 一个盒子不设置height,当内容子元素都浮动时,无法撑起自身
- 这个盒子没有形成BFC
如何创建BFC?
- 方法1:float的值不是none
- 方法2:position的值不是static或者relative
- 方法3:display的值时inline-block、flex、或者inline-flex
- 方法4:overflow:hidden
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
| <!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> .father{ overflow: hidden; } .son{ width: 200px; height: 200px; background-color: blue; float: left; } </style> </head> <body> <div class="father"> <div class="son"></div> <div class="son"></div> <div class="son"></div> </div> </body> </html>
|
BFC的其他作用
- BFC可以取消盒子margin塌陷
- BFC可以阻止元素被浮动元素覆盖(并不实用)
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
| <!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>取消塌陷</title> <style> .father{ width: 200px; height: 300px; background-color: blueviolet; overflow: hidden; } .son{ width: 100px; height: 100px; margin-top: 20px; background-color: blue; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> </body> </html>
|
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
| <!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>阻止覆盖</title> //浮动导致脱离文档流,下面的元素会上移而被覆盖,利用overflow可以阻止,但在开发中并没多大作用 <style> .son{ float: left; height: 100px; width: 100px; background-color: black; } .lastson{ height: 300px; width: 250px; background-color: aquamarine; overflow: hidden; } </style> </head> <body> <div class="son"></div> <div class="son"></div> <div class="lastson"></div> </body> </html>
|