BFC: 面试必问!!!!!
1. 什么是 BFC?
bfc 是块级格式上下文, 是一个网页的概念, 网页是一个盒子一个盒子 (div) 组成的.
2. 如何创建 BFC
1. 浮动: float:(left,right,inherit)除 none 以外的值[使用此属性注意左右距离是否被改变]
2. 定位: position(absolute,fixed)
3.display(inline-block, table-cell ,flex)
4.overflow(hidden, auto ,scroll)除 visible 以外的值
3. 产生 BFC 的事件:
在网页制作过程中由于浏览器加载是自上而下的原因, 外边距上下会取最大值, 左右不受影响.
栗子 1: 两个 DIV, 第一个 DIV 设置距离下边 20px; 第二个 DIV 设置距离上边 30px
按道理来说, 页面中的两个 div 上下距离应为 50px
- <div class="demo1">demo1</div>
- <div class="demo2">demo2</div>
- <style>
- .demo1{
- width: 200px;
- height: 200px;
- background-color: pink;
- margin-bottom: 20px;
- }
- .demo2{
- width: 200px;
- height: 200px;
- background-color: orange;
- margin-top: 30px;
- }
- </style>
结果确实两个 di'v 之间的距离只有 30px!!!!
什么原因呢?
这是因为浏览器解析的时候会使外边距叠加在一起, 这时候就是遇到了 BFC 问题
那么接下来就通过触发 BFC 来解决这个问题吧.
此处用个 box 给 div2 包住, 只通过一行代码(给 box 添加属性 position:absolute)ps:inherit 除外
- <div class="demo1">
- demo1
- </div>
- <div class="box">
- <div class="demo2">
- demo2
- </div>
- </div>
- <style>
- .demo1{ width: 200px; height: 200px; background-color: pink; margin-bottom:
- 20px; } .demo2{ width: 200px; height: 200px; background-color: orange;
- margin-top: 30px; } .box{ float: inherit;; }
- </style>
页面就正常啦~
栗子 2: 一个块中包含一个块, 设置这个子块的 margin:20px;
- <div class="box">
- <div class="demo">demo</div>
- </div>
- <style>
- .box{
- width: 200px;
- height: 200px;
- background-color: pink;
- }
- .demo{
- width: 100px;
- height: 100px;
- background-color: orange;
- margin: 20px;
- }
- </style>
页面效果如下:
解决办法: 触发 BFC(给父元素设置 overflow:hidden) ps:inherit 除外
- <style>
- .box{
- width: 200px;
- height: 200px;
- background-color: pink;
- overflow: hidden;
- }
- .demo{
- width: 100px;
- height: 100px;
- background-color: orange;
- margin: 20px;
- }
- </style>
酱紫就好啦~
来源: http://www.bubuko.com/infodetail-3496088.html