1.BFC定义和布局规则
BFC(Block formatting context)译为“块级格式化上下文”。它是一个独立的渲染区域,只有Block-level box参与,它规定了内部的Block-level如何布局,并且与这个区域外部毫不相干。
BFC布局规则
(1)内部的box会在垂直方向,一个接一个地放置
(2)Box垂直方向的距离有margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
(3)每个元素的margin box 的左边,会包含块border box的左边相接触(对于从左往右的格式化,否则相反),即使存在浮动也是如此
(4)BFC的区域不会与float box 重叠
(5)BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此
(6)计算BFC的高度时,浮动元素也参与计算
2.哪些元素会生成BFC
(1)根元素
(2)float属性不为none
(3)position为absolute或fixed
(4)display为inline-block,table-cell,table-caption,flex,inline-flex
(5)overflow不为visiable
3.B FC的作用及原理
(1)自适应两栏布局
代码:
<body> <div class="aside"></div> <div class="main"></div> </body>
页面:
根据BFC布局规则第三条:每个元素的margin box 的左边,会包含块border box的左边相接触(对于从左往右的格式化,否则相反),即使存在浮动也是如此,同时再根据BFC布局规则第四条:BFC的区域不会与float box 重叠。那我们就可以通过触发main生成BFC,从而实现自适应两栏布局
.main{ height: 200px; background-color: aqua; overflow:hidden; }
页面:
(2)清除内部浮动
代码:
<style> .content{ border:5px solid floralwhite; width: 300px; } .child{ border: 5px solid saddlebrown; width: 100px; height: 100px; float: left; } </style> <body> <div class="content"> <div class="child"></div> <div class="child"></div> </div> </body>
页面:
根据BFC布局规则第六条:计算BFC的高度时,浮动元素也参与计算。此时为了达到清除内部浮动,我们可以触发content触发生成BFC,那么content在计算高度时,content内部的浮动元素child也会参与计算
.content{ border:5px solid floralwhite; width: 300px; overflow:hidden; }
页面:
(3)防止垂直margin重叠
代码:
<style> p { color: salmon; background-color: seashell; width: 200px; line-height: 100px; text-align: center; margin: 100px; } </style> <body> <p>box1</p> <p>box2</p> </body>
页面:
上面两个模块之间发生了margin重叠,而根据BFC布局规则第二条:Box垂直方向的距离有margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠。这样的话我们可以在p 元素外面包裹一层容器,并触发该容器生成一个BFC。那么两个p元素不属于同一个BFC,就不会发生margin重叠了。
代码:
.wrap{ overflow: hidden; } p { color: salmon; background-color: seashell; width: 200px; line-height: 100px; text-align: center; margin: 100px; } <p>box1</p> <div class="wrap"> <p>box2</p> </div>
页面:
参考文字》》》https://www.cnblogs.com/lhb25/p/inside-block-formatting-ontext.html