BFC规范的一些理解

9 篇文章 0 订阅

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. In a block formatting> context, boxes are laid out one after the other, vertically, beginning> at the top of a containing block. The vertical distance between two> sibling boxes is determined by the ‘margin’ properties. Vertical> margins between adjacent block-level boxes in a block formatting> context collapse. In a block formatting context, each box’s left outer> edge touches the left edge of the containing block (for right-to-left> formatting, right edges touch). This is true even in the presence of> floats (although a box’s line boxes may shrink due to the floats),> unless the box establishes a new block formatting context (in which> case the box itself may become narrower due to the floats).


翻译成中文,就是浮动元素和绝对定位元素,非块级盒子的块级容器(inline-block,table-cell,table-caption)以及overflow值不为visible的块级盒子,都会为他们的内容创建新的块级格式化上下文。
在一个块级格式化上下文里,盒子从包含块的顶端开始垂直地一个接一个地排列,两个盒子之间的垂直间隙是由他们的margin值决定的。两个相邻的块级盒子的垂直外边距会发生叠加。
在块级格式化上下文中,每一个盒子的margin-left会触碰到容器的border-left,对于从右到左的格式则相反,即使存在浮动也是这样,除非这个盒子创建一个新的块级格式化上下文。
BFC是block fomatting context的缩写,就是块级格式化上下文,w3c里面还有inline formatting context,我们不妨继续看一下formatting context是个什么东西

**BFC有一下特性:**

1、内部的Box会在垂直方向,从顶部开始一个接一个地放置。
2、Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生叠加
3、每个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
4、BFC的区域不会与float box叠加。
5、BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素,反之亦然。
6、计算BFC的高度时,浮动元素也参与计算。

**那么我们怎样做就可以触发BFC呢**

 - float 除了none以外的值 overflow 除了visible 以外的值(hidden,auto,scroll )
 -  display (table-cell,table-caption,inline-block, flex, inline-flex)
 - position值为(absolute,fixed) fieldset元素
 - fieldset元素
在以上情况下可以创建BFC


BFC可以解决的问题
1、margin叠加的问题,我们将某个元素放到我们新建的BFC里面就可以避免margin叠加、
2、对于左右布局的元素,我们可以给右侧的元素添加overflow:hidden或者auto,左侧的是float:left
3、可以清除浮动,计算BFC高度,浮动元素不会撑开父元素的高度,我们可以让父元素触发BFC,即使用overflow:hidden 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值