css中BFC格式化上下文

来源:互联网 发布:linux 安装服务 编辑:程序博客网 时间:2024/06/10 03:21
参考:http://www.cnblogs.com/leejersey/p/4412785.html
什么是BFC
BFC(Block Formatting Context-块级格式化上下文),简单讲,它是提供了一个独立布局的环境,每个BFC都遵守同一套布局规则。例如,在同一个BFC内,盒子会一个挨着一个的排,相邻盒子的间距是由margin决定且垂直方向的margin会重叠。而float和clear float也只对同一个BFC内的元素有效。
什么情况产生BFC
W3C标准中这样描述:

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属性是visible之外任意值的块级盒子,都会创建了一个BFC。即当元素CSS属性设置了下列之一时,即可创建一个BFC:
  • float:left|right
  • position:absolute|fixed
  • display: table-cell|table-caption|inline-block
  • overflow: hidden|scroll|auto
<divclass=”item”><divclass=”pic”>your photo here?</div><pclass=”cont”> 爱饭否,爱豆瓣,也爱鸡脱壳。 爱爬山,爱拍美景。 爱腐败,更爱远征的自虐。 爱下雪天,爱感动,爱平底鞋。 我没有什么特别,我很特别。 我和别人不一样,我和你一样。 我是前端。</p></div>
.item{width:300px;border:1px solid #b2d1a3;background-color:#e5ebe4;}.pic{width:80px;height:80px;margin:10px; font-family:”Segoe UI Light”;color:#fff;}.cont{margin:10px;color:#37a;}
这时,如果要将文字部分放到图片的右侧,很多人都会想到给.pic使用float:
css:
.pic{width:80px;height:80px;margin:10px; font-family:”Segoe UI Light”;color:#fff; float:left;}
右侧内容并没有如我们预料一样规整的排在右侧,而是将左侧图片包围起来。接下来,我们为右侧内容部分设置overflow:hidden属性来使它形成一个新的BFC:
css:
.cont{margin:10px;color:#37a;overflow:hidden;}
这次将看到:

0 0
原创粉丝点击