BFC

BFC是什么

Block Formatting Context (块格式化上下文)

首先我们看看那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.

浮动元素和绝对定位元素,非块级盒子的块级容器(例如 inline-blocks, table-cells, 和 table-captions),以及overflow值不为“visiable”的块级盒子,都会为他们的内容创建新的BFC(块级格式上下文)。

在BFC中,盒子从顶端开始垂直地一个接一个地排列,两个盒子之间的垂直的间隙是由他们的margin 值所决定的。在一个BFC中,两个相邻的块级盒子的垂直外边距会产生折叠。

 

什么时候创建BFC 

float 除了none以外的值 
overflow 除了visible 以外的值(hidden,auto,scroll ) 
display (table-cell,table-caption,inline-block, flex, inline-flex) 
position值为(absolute,fixed) 
fieldset元素 

我们通过一个实例看看

BFC

<div style="background-color: green;width: 300px;height: 300px ">
<div style="background-color: red;width: 50px;height: 50px;float: left">
</div>
 <p>
sssssdddddddddddddddddddddddddd
sssssdddddddddddddddddddddddddd
sssssdddddddddddddddddddddddddd
sssssdddddddddddddddddddddddddd
sssssdddddddddddddddddddddddddd
sssssdddddddddddddddddddddddddd

</p>
</div>

我们让文字位于红色模块的右侧,通常采用浮漂float,添加float

 <div style="width: 50px;height: 50px;float: left">

结果:BFC

 

在红色模块的下面并没让文字靠右。这个时候我们得给文字添加overflow: hidden,生成一个BFCBFC这个就是我们想要的结果。

 <p style="overflow: hidden">

你可能感兴趣的:(c)