写在最前:BFC看起来是个很陌生的概念但它却时时发生在咱们工做中,如何清除浮动影响?如何避免margin穿透问题?如何编写两栏自适应布局?都和BFC有这密不可分的关系,下面走进切图妞的世界,分分钟搞定BFC!
BFC概念html
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其余元素交互的区域。简而言之,BFC就是一种边距重叠的解决方案。git
BFC原理github
主流:浏览器
float+float具备包裹性和破坏性致使没法自适应,通常用在块状浮动布局
)absolute脱离文档流
)overflow可自适应,但因为溢出不可见限制了应用场景
)inline-block具备包裹性,没法自适应,IE8如下没法识别该属性
)table-cell具备包裹性,无溢出特性,绝对宽度也能自适应
)非主流:ide
写样式的时候经常怀疑个人margin是被浏览器吞掉了吗?
做为一个子元素想离父元素上边距有50px的距离,正常状况下是这么显示的布局
<section class="sec" style="overflow:hidden"> <article class="child">height: 50px;margin-top: 50px;</article> </section>
.sec { background: #ebf6fd; } .child { height: 50px;background: #09d;margin-top: 50px; line-height: 50px;}
子元素的margin-top值由于穿透问题没有实现预想效果flex
解决方法:使父元素变为BFC,添加overflow:hidden的样式,就会实现以下效果
<section class="sec" style="overflow:hidden"> <article class="child">height: 50px;margin-top: 50px;</article> </section>
书写列表结构的时候,margin-top为20px,margin-bottom为20px,预想中应该出现40px的效果,可是正常状况下是这样的:url
<section class="margin"> <p>切图妞切图妞切图妞切图妞切图妞切图妞切图妞</p> <p>切图妞切图妞切图妞切图妞切图妞切图妞切图妞</p> </section>
.margin {background: #ebf6fd;} .margin p { margin: 20px auto;background: #09d; line-height: 40px;}
margin-top和margin-bottom在垂直方向的边距会发生重叠现象,margin-top和margin-bottom哪一个大就间隔哪一个的距离。spa
解决方法:给子元素再建立一个父元素,使父元素是BFC
<section class="margin"> <div style="overflow:hidden"> <p>切图妞切图妞切图妞切图妞切图妞切图妞切图妞</p> </div> <div style="overflow:hidden"> <p>切图妞切图妞切图妞切图妞切图妞切图妞切图妞</p> </div> </section>
图片与文字组合的结构,咱们常常会使图片浮动起来,利用float的包裹性,让文字环绕图片,以下:3d
<section class="layout"> <img src="img/bqb1.jpg" class="left" alt="" /> <div class="right"> 傻人有傻福 </div> </section>
.layout {background: #ebf6fd;margin-top: 20px;} .layout .left { float: left; width: 150px;height: 168px;} .layout .right {background: #09d;text-align: left; }
可是当咱们想把图片和文字的区块独立分来一左一右的时候呢?
解决方法:使右侧元素为BFC,添加overflow:hidden的样式
img src="img/bqb1.jpg" class="left" alt="" /> <div class="right" style="overflow:hidden"> 傻人有傻福 </div> </section>
当咱们须要图片与文字间距20px时,有两种方法:左侧margin-right或者右侧padding-left
<img src="img/bqb1.jpg" class="left" style="margin-right:20px" />
<div class="right" style="overflow:hidden;padding-left:20px"> 傻人有傻福 </div>
父元素包含浮动元素,致使父元素塌陷,正常状况以下:
<section class="floatBorder"> <div class="float">切图妞切图妞切图妞切图妞切图妞切图妞切图妞</div> </section>
.floatBorder { background: #ebf6fd;border: 1px solid #FFBE00;margin-top: 20px;} .floatBorder .float { float: left; line-height: 50px; background: #08d;}
父元素塌陷除了border外失去高度,此时须要利用BFC内子元素即便是浮动元素也会参与计算的原理
解决方法:使父元素变成BFC,添加清除浮动类
.clearfix {*zoom: 1 } .clearfix:after {content: '';display: table; clear: both }
具备BFC属性的元素是一个独立的容器,它不受子元素影响也不影响子元素!当margin遇到BFC,边距重叠问题得以解决;当BFC元素身边存在浮动时,它拒绝了float的包裹性独立成一个容器不与其重叠;当浮动元素在BFC元素里面时,计算高度时将内部浮动元素也进行计算,解决了父元素塌陷的问题!
上面示例代码已上传,可下载练习修改→BFC Demo
尊重原创,如需转载请注明出处!