「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。
前言
在前端的面试中BFC是一个老生常谈的话题,那什么是BFC?应该如何理解?当面试管在问我们BFC的时候我们应该如何回答?成了我们最最最关心的问题。接下来我会用大白话为大家一一讲解。
什么是BFC?
首先直接翻译一下BFC,BFC全称 Block Formatting Contexts,中文意思为:块级格式化上下文。BFC是一块独立的布局环境,保护其中内部元素不受外部影响,也不影响外部。本身BFC是一种css的布局方式,只是我们可以利用它来解决外边距折叠的问题,BFC并不是专门用来解决这个问题而创的;
通俗一点来讲,可以把BFC理解为一个封闭的大盒子,盒子内部的元素无论怎么样,是跑,是跳、还是飞,都不会影响到外部。
如何触发BFC?
- 浮动元素:float除none以外的值
- 绝对定位元素:position(absolute、fixed)
- display为inline-block、table-cells、flex
- overflow除了visible以外的值(hidden、auto、scroll)
什么是边距重叠?
两个box如果都设置了边距,那么在垂直方向上,两个box的边距会发生重叠,以绝对值大的那个为最终结果显示在页面上;
举例说明(使用)
- 如果一个子元素 一个父元素, 如果子元素设置了margin-top 在没有把父元素变成BFC的情况下 父元素也会产生外边距。
解决方案:给父元素添加 overflow:hidden
这样父元素就变为 BFC不会随子元素产生外边距
<style>
.box {
width: 200px;
height: 200px;
background-color: #f00;
}
.inner{
margin-top: 50px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
<div class="box">
<div class="inner"></article>
</div>
- 如果两个盒子都一样大 一个盒子设置margin-bottom 50px,另一个盒子设置margin-top 是20 ,那肯定会取最大值的那个。 解决方案:可通过添加空元素或伪类元素,设置overflow:hidden; 解决 margin 重叠问题
<style>
.box {
background-color: #ccc;
}
.box .child-one {
width: 100px;
height: 100px;
margin-bottom: 50px;
background-color: #f00;
}
.box .child-two {
width: 100px;
height: 100px;
margin-top: 20px;
background-color: #345890;
}
.box .child-three {
overflow:hidden
}
</style>
<section class="box">
<div class="child-one"></div>
<div class="child-two"></div>
<div class="child-three"></div>
</section>
结束语
如果你觉得该文章不错,不妨点个赞吧。