概念
块级元素在BFC布局(块级格式化上下文)
行内级元素在IFC布局(行内级格式化上下文)
BFC
形成BFC的情况
BFC规则
- 在BFC中box在垂直方向排列
- 在同一个BFC中,相邻box垂直方向外边距塌陷
- 在BFC中box左边缘紧贴包含块的左边缘
BFC应用
- 解决外边距折叠
<!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>div {width: 200px;height: 200px;}.box1 {margin-bottom: 100px;background-color: pink;}.box2 {margin-top: 100px;background-color: #bfa;;}</style>
</head><body><div class="box1"></div><div class="box2"></div>
</body></html>
box1和box2都在html下,属于同一个BFC,存在外边距折叠问题
<!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>.container {overflow: hidden;}.box1 {width: 200px;height: 200px;margin-bottom: 100px;background-color: pink;}.box2 {width: 200px;height: 200px;margin-top: 100px;background-color: #bfa;;}</style>
</head><body><div class="container"><div class="box1"></div></div><div class="box2"></div>
</body></html>
box1在container形成的BFC下,box2在html元素的BFC下,不再同一个BFC下,外边距不塌陷
- 解决浮动元素高度塌陷
<!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>.container {/* 形成BFC,增加高度以包含这些浮动元素的下边缘*/overflow: hidden;background-color: #bfa;}.container>.item {float: left;width: 200px;height: 200px;background-color: pink;border: 1px solid #000;}</style>
</head><body><div class="container"><div class="item"></div><div class="item"></div><div class="item"></div></div>
</body></html>