BFC 格式化上下文

79 阅读1分钟

一、何为BFC(独立空间、流动元素)

  • BFC(Block Formatting Context)格式化上下文
  • 形成一个独立的渲染空间,子元素不受外部元素影响

二、形成BFC的条件

  • 浮动元素:float 除 none 以外的值;
  • position:position(absolute,fixed);
  • display
    • inline-block、table-cell、table-caption、table、
    • inline-table、flex、inline-flex、grid、inline-grid
  • overflow
    • 除了 visible 以外的值
    • hidden,auto,scroll

三、BFC的特性

  • 内部的 Box 会在垂直方向上一个接一个的放置
  • 垂直方向上的距离由margin决定( 同一个bfc的两个相邻box的margin会重叠 )
  • " bfc的区域 " 不会被 float 的元素区域重叠
  • 计算bfc的高度时,浮动元素也参与计算

四、应用

解决外边距重叠问题(防⽌元素塌陷)
  • 添加 wrapper ,防止 container 元素塌陷的问题
  • 添加 wrapper ,方式 box1 和 box2 的 重叠问题
<div class="container">
  <div class="wrapper">
    <div class="box1"></div>
  </div>
  <div class="box2"></div>
</div>
.container {
  width: 100px;
  height: 100px;
  background-color: red;
}

.wrapper {
  overflow: hidden;
  /* 形成BFC,格式化上下文 */
}

.wrapper .box1 {
  height: 20px;
  margin: 10px 0;
  background-color: green;
}

.box2 {
  height: 20px;
  margin: 20px 0;
  background-color: green;
}
解决流式布局
<div class="contain">
  <!-- 前两个 - 左右浮动 -->
  <div class="pre flot"></div>
  <div class="middle flot"></div>
    <!-- 最后 - 流动布局 -->
  <div class="next"></div>  
</div>
.flot {
  float: left;
  width: 100px;
  height: 300px;
  background-color: green;
  margin-right: 15px;
}

.middle {
  float: right;
  margin-right: 0px;
  margin-left: 15px;
}

.next {
  overflow: hidden;
  /* 形成BFC,格式化上下文 */
  height: 300px;
  background-color: red;
}