Skip to content

Commit 0871911

Browse files
committed
chore(ci): blog sync
1 parent 70f0503 commit 0871911

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

data/blog/BFChegaodutaxian.mdx

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
title: BFC和高度塌陷
3+
date: 2023-12-23T12:50:54Z
4+
summary:
5+
tags: []
6+
---
7+
8+
## 高度塌陷
9+
我们知道,如果一个块级元素没有设置固定的高度,那么它的高度会被高度最大的子元素撑起,如下:
10+
在容器中有 box1 和 box2 两个元素,容器的高度被 box1 撑起
11+
12+
<div style="background-color: aqua;display:flex">
13+
<div style="height:100px;width:100px;background-color: red;line-height:100px;text-align:center;color:white">box1</div>
14+
<div style="height:50px;width:150px;background-color: blue;line-height:50px;text-align:center;color:white">box2</div>
15+
</div>
16+
17+
如果给 box1 添加浮动、定位等,使其脱离了正常的文档流,即产生了高度塌陷
18+
19+
<div style="background-color: aqua;">
20+
<div style="height:100px;width:100px;background-color: red;line-height:100px;text-align:center;color:white;float: left;">box1</div>
21+
<div style="height:50px;width:150px;background-color: blue;line-height:50px;text-align:center;color:white">box2</div>
22+
</div><br>
23+
24+
## 外边距塌陷
25+
外边距塌陷也称为外边距合并,是指两个在正常流中相邻(兄弟或父子关系)的块级元素的外边距,组合在一起变成单个外边距,不过只有上下外边距才会有塌陷,左右外边距不会出现这种问题。
26+
### 兄弟元素
27+
<div style="margin-bottom: 5px; background-color: rgb(255, 147, 147)">
28+
一寸光阴一寸金
29+
</div>
30+
<div style="margin-top: 30px; background-color: rgb(159, 159, 255)">
31+
寸金难买寸光阴
32+
</div>
33+
34+
```
35+
<div style="margin-bottom: 5px; background-color: rgb(255, 147, 147)">
36+
一寸光阴一寸金
37+
</div>
38+
<div style="margin-top: 30px; background-color: rgb(159, 159, 255)">
39+
寸金难买寸光阴
40+
</div>
41+
```
42+
可以看到在有相邻 `margin-bottom``margin-top` 时,他们只会保留边距大的一个,而不是将其累加
43+
### 父子元素
44+
<div style="background-color: rgb(224,224,224);height:300px;display:flow-root">
45+
<div style="background-color: rgb(122,122,222);width:200px;height:200px;">
46+
<div style="background-color: rgb(122,22,122);width:100px;height:100px;margin-top: 20px;"></div>
47+
</div>
48+
</div>
49+
这种现象我们应该经常会遇到,无论是给父元素还是子元素边距,他们都会有边距。
50+
以上情形都可以通过 BFC 解决,那么什么是 BFC ?
51+
52+
## BFC(块级格式化上下文)
53+
BFC(Block formatting context)直译为“块级格式化上下文”。BFC 它是一个独立的渲染区域,只有Block-level box(块元素)参与,它规定了内部的Block-level box如何布局,并且与这个区域外部毫不相关。
54+
简单的来说 BFC是一个与世隔绝的盒子,其内部元素对外部布局不产生影响,并且 BFC 里的脱离文本流的元素会按照正常流进行布局。
55+
那么如何创建 BFC
56+
+ over-flow:除visible以外的值
57+
+ 浮动
58+
+ position:除static和relative以外的值
59+
+ display:除grid、inline-grid和inline以外的值
60+
61+
## 总结
62+
合理的运用 BFC 能解决很多的布局问题,如:浮动未清除的影响,外边距重叠,文字的环绕等。
63+

0 commit comments

Comments
 (0)