三个概念:
BOX: 普通流/标准流中的 Box(框) 属于一种 formatting context(格式化上下文) block inline
BFC:(Block Formatting Context)块级格式上下文
IFC:(Inline Formatting Context)即行内格式化上下文
BFC就是一种布局方式,在这种布局方式下,
盒子们自所在的containing block顶部一个接一个垂直排列,水平方向上撑满整个宽度(除非内部盒子自己建立了新的BFC)。
两个相邻的BFC之间的距离由margin决定。在同一个BFC内部,两个垂直方向相邻的块级元素的margin会发生“塌陷”。
解决:给子元素也加bfc
触发条件:
条件 | 语义 |
---|---|
html | 根元素 |
浮动元素 | 不为 none |
定位元素 | absolute,fixed |
display | inline-block,table-cell,table-caption,flex/inlineflex,grid 或 inline-grid, (flow-root它可以创建无副作用的 BFC) |
overflow | 除了 visible 以外的值 |
多列容器 | 这个没了解可以看MDN描述 |
flex 或grid 包括他的子元素
作用:
- 内部的Box会在垂直方向上一个接一个的放置。
- 垂直方向上的距离由margin决定
- bfc的区域不会与float的元素区域重叠。
- 计算bfc的高度时,浮动元素也参与计算
- bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素
举例:
6. 外边距折叠
<div class="containter">
<div class="box1"></div>
<div class="box2"></div>
</div>
.containter {
width: 100%;
height: 600px;
}
.box1 {
width: 300px;
height: 100px;
background-color: pink;
margin: 10px 0;
}
.box2 {
width: 300px;
height: 100px;
background-color: red;
margin: 20px 0;
}
.w {
overflow: hidden;
}
此时就会大边距小边距,
让box1或者box2 在一个bfc里面就可以解决这个问题。
<div class="containter">
<div class="w">
<div class="box1"></div>
</div>
<div class="box2"></div>
</div>
- 不和浮动元素重叠,清除外部浮动,阻止浮动元素覆盖
如果一个浮动元素后面跟着一个非浮动的元素,那么就会产生一个重叠的现象
.containter {
width: 100%;
height: 600px;
}
.box1 {
width: 100px;
height: 100px;
background-color: pink;
float: left;
}
.box2 {
width: 300px;
height: 200px;
background-color: red;
}
<div class="containter">
<div class="box1"></div>
<div class="box2"></div>
</div>
解决:
box2 {overflow:hidden;}
还有经典的两行三行布局可看上一篇文章:https://blog.csdn.net/weixin_44002250/article/details/120734894
- 环绕:
<style>
.containte {
width: 300px;
border: 1px solid blue;
height: 300px;
}
.box1 {
width: 100px;
height: 100px;
background-color: pink;
float: left;
margin: 5px;
}
p {
background-color: green;
overflow: hidden;/*BFC*/
}
</style>
</head>
<body>
<div class="containte">
<div class="box1">1</div>
<p>jffcgbvvbjgggggggggggggggggggggggggrrrrrrrrrrrrrrrrrrrrrrgggggggggggggggggggggggg</p>
</div>
</body>