◼ MDN上有整理出在哪些具体的情况下会创建BFC:
- 根元素()
- 浮动元素(元素的 float 不是 none)
- 绝对定位元素(元素的 position 为 absolute 或 fixed)
- 行内块元素(元素的 display 为 inline-block)
- 表格单元格(元素的 display 为 table-cell,HTML表格单元格默认为该值),表格标题(元素的 display 为 table-caption,HTML表格标题默认为该值)
- 匿名表格单元格元素(元素的 display 为 table、table-row、 table-row-group、table-header-group、table-footer-group(分别是HTML table、row、tbody、thead、tfoot 的默认属性)或 inline-table)
- overflow 计算值(Computed)不为 visible 的块元素
- 弹性元素(display 为 flex 或 inline-flex 元素的直接子元素)
- 网格元素(display 为 grid 或 inline-grid 元素的直接子元素)
- display 值为 flow-root 的元素
- 作用:
- 在BFC中,box会在垂直方向上一个挨着一个的排布;
- 垂直方向的间距由margin属性决定;
- 在同一个BFC中,相邻两个box之间的margin会折叠(collapse);
- 在BFC中,每个元素的左边缘是紧挨着包含块的左边缘的;
- 作用:
margin 塌陷的解决
<!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>
</head>
<style>
.container {
overflow: hidden;
}
.box1 {
height: 200px;
background-color: orange;
margin-bottom: 50px;
}
.box2 {
height: 100px;
background-color: pink;
margin-top: 20px;
}
</style>
<body>
<!-- fc formatting Context 格式化上下文 -->
<!-- 元素在标准流里面都是属于一个FC -->
<div class="container">
<div class="box1"></div>
</div>
<div class="box2"></div>
<p>
<a href="#">
</a>
<span></span>
</p>
</body>
</html>
浮动高度的解决
<!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 {
position: relative;
/* position: absolute; */
background-color: orange;
overflow: auto;
}
.item {
/* position: absolute; */
width: 400px;
height: 200px;
box-sizing: border-box;
border: 1px solid #000;
float: left;
background-color: antiquewhite;
}
/* .clear_fix::after {
content: "";
display: block;
clear: both;
height: 0;
visibility: hidden;
}
.clear_fix {
*zoom: 0
} */
</style>
</head>
<body>
<div class="container clear_fix">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
</body>
</html>