BFC 总结

理解定义

BFC(Block formatting context)"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干。

BFC6条规则

  1. 内部的Box会在垂直方向,一个接一个地放置。
  2. Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
  3. 每个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
  4. BFC的区域不会与float box重叠。
  5. BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
  6. 计算BFC的高度时,浮动元素也参与计算

如何生成BFC

  1. 根元素
  2. float属性不为none
  3. position为absolute或fixed
  4. display为inline-block, table-cell, table-caption, flex, inline-flex
  5. overflow不为visible

查找的BFC几个应用

  1. 自适应两栏布局

    <style>
     body {
         width: 300px;
         position: relative;
     }
    
     .aside {
         width: 100px;
         height: 150px;
         float: left;
         background: #f66;
     }
    
     .main {
         height: 200px;
         background: #fcc;
     }
    </style>
    <body>
     <div class="aside"></div>
     <div class="main"></div>
    </body>
    

    BFC的区域不会与float box重叠。

  2. 清除内部浮动

<style>
    .par {
        border: 5px solid #fcc;
        width: 300px;
        // 父元素生成bfc
    }

    .child {
        border: 5px solid #f66;
        width:100px;
        height: 100px;
        float: left;
    }
</style>
<body>
    <div class="par">
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>

计算BFC的高度时,浮动元素也参与计算

  1. 防止垂直 margin 重叠
    <style>
     .wrap {
         overflow: hidden;
     }
     p {
         color: #f55;
         background: #fcc;
         width: 200px;
         line-height: 100px;
         text-align:center;
         margin: 100px;
     }
    </style>
    <body>
     <p>Haha</p>
     <div class="wrap">
         <p>Hehe</p>
     </div>
    </body>
    

    Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠

results matching ""

    No results matching ""