BFC(Block Formatting Context),块级格式化上下文,它规定了内部的块级元素的布局方式,默认情况下只有根元素(即body)一个块级上下文。
⾸先我们要知道怎样创建 BFC。一个BFC可以被显式触发,只需满⾜以下条件之一
BFC特性
在常规文档流中,两个兄弟盒子之间的垂直距离是由他们的外边距所决定的,但不是他们的两个外边距之和,⽽是以较大的为准。
<style>
.container {
overflow:hidden;
width:100px;
height:100px;
background:red;
}
.box1 {
height:20px;
margin:10px 0;
background:green;
}
.box2 {
height:20px;
margin:20px 0;
background:blue;
}
.box3{
overflow:hidden;
}
</style>
<div class="container">
<div class="box1"></div>
<div class="box3">
<div class="box2"></div>
</div>
</div>
可以看到,第一个子盒子有上边距;两个子盒子的垂直距离为20px⽽不是30px,因为垂直外边距会折叠,间距以较大的为准。
那么如何让垂直外边距不折叠呢?
特性中提到:BFC就是页面上的一个独立容器,容器里面的子元素不会影响外面元素,同样外面的元素不会影响到BFC内的元素。所以就让box1或box2再处于另一个BFC中就行了。
<style>
.outside{
border: 10px solid blue;
overflow: hidden;
}
.inside{
float: left;
width: 200px;
height: 200px;
background: yellowgreen;
}
</style>
<div class="outside">
<div class="inside"></div>
</div>
<style>
.left {
float: left;
width: 100px;
height: 200px;
background: yellowgreen;
}
.right {
height: 300px;
background: blue;
overflow:hidden;
}
</style>
<div class="left"></div>
<div class="right"></div>
<style>
.left {
float: left;
width: 100px;
height: 300px;
background: yellowgreen;
}
.center {
height: 300px;
background: red;
overflow: hidden;
}
.right {
float:right;
width: 100px;
height: 300px;
background: blue;
overflow: hidden;
}
</style>
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
左右两边固定宽度,中间不设宽,因此中间的宽度⾃适应,随浏览器的大⼩变化⽽变化。
<style>
.outside {
border: 10px solid blue;
}
.inside {
width: 200px;
height: 200px;
background: yellowgreen;
}
</style>
<div class="outside">
<div class="inside"></div>
<div class="inside"></div>
<div class="inside"></div>
</div>
浮动的盒子会遮盖下⾯的盒子,但是下⾯盒子⾥的文字是不会被遮盖的,文字反⽽还会环绕浮动的盒子。这也是一个⽐较有趣的特性。
<style>
.left {
float: left;
width: 100px;
height: 100px;
background: yellowgreen;
}
p {
background: red;
overflow: hidden;
}
</style>
<div class="left"></div>
<p>你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好</p>
1、实现两栏布局,三栏布局
2、实现文字环绕效果