什么是BFC
BFC(Block formatting context):"块级格式化上下文"是一个独立渲染的区域。
BFC的布局规则
-
内部的盒子会在垂直方向,一个接一个地放置。
-
盒子垂直方向的距离由margin决定。属于同一个BFC的两个相邻盒子的margin会发生重叠。
-
每个盒子的margin box的左边,与包含块()border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
-
BFC的区域不会与float box重叠。
-
BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
-
计算BFC的高度时,浮动元素也参与计算。
如何创建BFC
1.float不为none
2.position为absolute和fixed
3. display为inline-block,flex,table-cell table-caption ,inline-flex
4. overflow不为visible
BFC作用
1.利用BFC避免margin重叠。
<style>
*{
margin: 0;
padding: 0;
}
p {
color: white;
background: orange;
width: 200px;
line-height: 100px;
text-align:center;
margin: 30px;
}
#app{
overflow: hidden;
}
</style>
<body>
<p>1111</p>
<div id="app">
<p>2222</p>
<p>3333</p>
</div>
</body>
2.左右固定中间自适应布局
<style>
*{
margin: 0;
padding: 0;
}
body {
width: 100%;
position: relative;
}
.left {
width: 100px;
height: 150px;
float: left;
background-color: skyblue;
text-align: center;
line-height: 150px;
font-size: 20px;
}
.top{
height: 300px;
background-color: #aa36ec;
text-align: center;
line-height: 300px;
font-size: 40px;
overflow: hidden;
}
.right {
width: 100px;
height: 150px;
float: right;
background-color: skyblue;
text-align: center;
line-height: 150px;
font-size: 20px;
}
</style>
<body>
<div class="left">LEFT</div>
<div class="right">RIGHT</div>
<div class="top">TOP</div>
</body>