BFC块级格式化上下文

134 阅读1分钟
  • 块级格式化上下文,它是指一个独立的块级渲染区域,只有Block-level BOX(块级类型的盒子)参与,该区域拥有一套渲染规则来约束块级盒子的布局,且与区域外部无关

  • 一个盒子不设置height,当内容子元素都浮动时,无法撑起自身,这个盒子没有行程BFC

    .son{
    	width: 300px;
    	height: 300px;
    	background: red;
    	float: left;       // 此时外层盒子高度为0
    }
    .father{
    	overflow: hidden; // 如果这样写,父盒子就有高度了
    }
    
  • 如何创建BFC

    1. float的值不是none
    2. position的值不是static或者relative(absolute、fixed)
    3. display的值是inline-block、flex或者inline-flex
    4. overflow:hidden(这个最好,因为如果设置为inline-block,后面的元素会变为一行)
  • BFC的其他作用

    • 1、BFC可以取消盒子margin塌陷

      .father{
      	width: 200px;
      	height: 300px;
      	background: red;
      	// 解决:overflow: hidden; 创建BFC
      }
      .son{
      	width: 100px;
      	height: 100px;
      	background: blue;
      	margin-top: 20px; //希望son距离father20px,但是结果是father离顶部20px
      }
      
    • 2、BFC可以阻止元素被浮动元素覆盖

      .son{
      	width: 200px;
      	heght: 200px;
      	background: red;
      	float: left;
      }
      .son-last{
      	width: 200px;
      	heght: 300px;
      	background: blue; // 结果会钻到前面两个son的底下
      	// 解决:overflow:hidden;
      }