面试必会知识BFC
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with ‘overflow’ other than ‘visible’ (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
浮动元素和绝对定位元素,非块级盒子的块级容器(例如 inline-blocks, table-cells, 和 table-captions),以及overflow值不为“visiable”的块级盒子,都会为他们的内容创建新的BFC(块级格式上下文)。
一般也就是:
1、根元素
2、float属性不为none
3、position为absolute或fixed
4、display为inline-block, table-cell, table-caption, flex, inline-flex
5、overflow不为visible
阻止元素被浮动的元素覆盖,自适应成两栏布局
<div class="ldiv">
左浮动的元素
div>
<div class="rdiv">
没有设置浮动, 没有设置宽度 width
但是触发 BFC 元素
div>
<style>
.ldiv {
height: 100px;
width: 100px;
float: left;
background: aqua;
}
.rdiv {
height: 100px;
background: blueviolet;
overflow: hidden;
}
style>
解决浮动元素不占高度的问题(浮动元素未被包裹在父容器)
<div class="parent">
<div class="child">div>
div>
<style>
.parent {
border: 1px solid blueviolet;
overflow: hidden;
}
.child {
width: 100px;
height: 100px;
background: aqua;
float: left;
}
style>
为了防止 margin 重叠, 可以使多个 box 分属于不同的 BFC 时
<div class="container">
<p>p>
div>
<div class="container">
<p>p>
div>
<style>
.container {
overflow: hidden;
}
p {
width: 100px;
height: 100px;
background: aqua;
margin: 10px;
}
style>
<div class="ldiv">
左浮动的元素
div>
<div class="rdiv">
没有设置浮动, 但是触发 BFC 元素
div>
<style>
.ldiv {
height: 100px;
width: 100px;
float: left;
background: aqua;
}
.rdiv {
width: 300px;
height: 200px;
background: blueviolet;
overflow: hidden;
}
style>