首先,什么是BFC?
答:BFC(Block formatting context),中文名:块级格式化上下文,一定记住它是一个独立的渲染区域。
接下来,我们说说BFC能解决些什么样的问题
1、边距重叠问题
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
border: 1px solid red
}
.top {
margin-bottom: 30px;
}
.bottom {
margin-top: 10px;
}
<body>
<div class="top">1</div>
<div class="bottom">2</div>
</body>
如上代码中,我们想要的效果是div1有30px的margin-bottom,div2有10px的margin-top,两个div之间的间距应该是40px。但是如下图,我们只得到30px的margin。这里的两个margin就重叠了,最终取较大值为实际margin。
既然有问题,那么我们就要解决
- 给其中一个盒子添加 display: inline-block
.top {
display: inline-block;
margin-bottom: 30px;
}
2、盒子塌陷问题
* {
margin: 0;
padding: 0;
}
.father {
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 100px;
height: 100px;
margin-top: 20px;
background-color: yellow;
}
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
如上代码中,我们期望的效果是子盒子距离父盒子有一个20px的margin-top,然而实际效果是20px的margin-top作用到了父盒子上
- 解决办法,给父盒子加overflow:hidden
.father {
width: 200px;
height: 200px;
overflow: hidden;
background-color: red;
}
3、清除浮动
* {
margin: 0;
padding: 0;
}
.son {
width: 100px;
height: 100px;
float: left;
background-color: yellow;
}
.bottom {
width: 300px;
height: 200px;
background-color: red;
}
<body>
<div class="father">
<div class="son"></div>
<div class="son"></div>
</div>
<div class="bottom"></div>
</body>
如上代码,我们想要的效果是 bottom(红色) 盒子排在 father 盒子的下面,然而却因为浮动使其重叠在了一起
- 解决办法,给father盒子添加overflow:hidden
.father {
overflow: hidden;
}
4、浮动环绕文字
* {
margin: 0;
padding: 0;
}
.box{
width: 100px;
height: 100px;
float: left;
background-color: red;
}
.father{
width: 200px;
}
<body>
<div class="father">
<div class="box"></div>
<div class="message">我是文字我是文字我是文字我是文字我是文字我是文字我是文字我是文字我是文字我是文字</div>
</div>
</body>
如上代码,我们想要的效果是文字排在box盒子的右边
- 解决办法,给message盒子添加 overflow:hidden
总结
如上几个问题,我们的解决办法都是为其创建一个独立的渲染区域,这个区域也被称为块级格式化上下文,也就是BFC
创建BFC的方法有:
1、float属性不为none
2、position 为 absolute fixed
3、display 为 inline-block table-cell flex
4、overflow 为 hidden auto scroll