什么是BFC
BFC(Block formatting context)直译为“块级格式化上下文”。它是一个独立的渲染区域,只有Block-level box(块)参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干。
BFC 的布局规则
一、内部的Box会在垂直方向,一个接一个地放置。
二、Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠(按照最大margin值设置)
三、每个元素的margin box的左边, 与包含块border box的左边相接触
四、BFC的区域不会与float box重叠。
五、BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。
六、计算BFC的高度时,浮动元素也参与计算
标题哪些元素和属性能触发BFC?
一、根元素(html)
二、float属性不为none
三、position为absolute或fixed
四、display为inline-block, table-cell, table-caption, flex, inline-flex
五、overflow不为visible
BFC的应用
一、自适应两栏布局
方法如下
<style>
body {
width: 300px;
position: relative;
}
.box1{
width: 100px;
height: 150px;
float: left;
background: #f66;
}
.box2 {
height: 200px;
background: #fcc;
overflow: hidden;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
二、清除内部浮动
方法如下
<style type="text/css">
.box{
width:600px;
height: auto;
border:2px solid #f00;
margin:30px auto;
overflow:hidden;
}
.content1{
height:200px;
width: 200px;
background:#f0f;
float:left;
}
.content2{
height:200px;
width: 350px;
background:#0ff;
float: right;
}
</style>
</head>
<body>
<div class="box">
<div class="content1"></div>
<div class="content2"></div>
</div>
</body>
三、防止margin上下重叠
<style>
p {
color: #f55;
background: #fcc;
width: 200px;
line-height: 100px;
text-align:center;
margin: 100px;
}
</style>
<body>
<p>holle world</p>
<p>NICE</p>
</body>