什么是BFC#
bfc的全稱為Block Formatting Contexts荔睹,即塊級(jí)格式化上下文,W3C是這么定義BFC的
https://www.w3.org/TR/CSS2/visuren.html#block-formatting
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).
簡單解釋就是脯宿,BFC在頁面上創(chuàng)建了一個(gè)獨(dú)立的單元,內(nèi)部元素不會(huì)影響外部元素的胁塞,而外部元素也不會(huì)影響到內(nèi)部元素
觸發(fā)BFC的方法:###
- 浮動(dòng)元素和position屬性為absolute的元素
- 非塊級(jí)盒子的塊級(jí)容器够颠,如display屬性為inline-block,table-cells和table-captions的元素
- overflow屬性不為visible的塊級(jí)盒子(最常用的是overflow: hidden)
BFC的特性:###
- 在一個(gè)BFC中的塊級(jí)元素會(huì)從垂直的從上到下排列
- 相鄰的兩個(gè)盒子的間隙是由margin屬性決定的
- 相鄰的盒子垂直方向的margin會(huì)產(chǎn)生重疊現(xiàn)象
- 每個(gè)盒子的左邊緣會(huì)觸碰到容器的左邊緣(自右向左的除外)
BFC的應(yīng)用:###
- 消除float的文字環(huán)繞效果
這里圖片左浮動(dòng),文字內(nèi)容自動(dòng)環(huán)繞
我們給包裹文字的div添加屬性overflow: hidden
- 消除margin重疊效果
這里每個(gè)紅色的div都設(shè)置了上下各20px的外邊距吁朦,可以看出在中間處發(fā)生了margin重疊
而我們給下面這個(gè)紅色的div外面加個(gè)div并設(shè)置overflow: hidden屬性
重疊效果被消除了
結(jié)束之言:#
關(guān)于BFC的總結(jié)柒室,小生就說這么多吧。本文僅供參考逗宜,歡迎大家一起來交流