CSS中BFC

BFC(Block Formatting Context)格式化上下文,是Web页面中盒模型布局的CSS渲染模式,指一个独立的渲染区域或者说是一个隔离的独立容器。
形成条件:
1、浮动元素,float 除 none 以外的值;
2、定位元素,position(absolute,fixed);
3、display 为以下其中之一的值 inline-block,table-cell,table-caption;
4、overflow 除了 visible 以外的值(hidden,auto,scroll);
特性:
1.内部的Box会在垂直方向上一个接一个的放置。
2.垂直方向上的距离由margin决定
3.bfc的区域不会与float的元素区域重叠。
4.计算bfc的高度时,浮动元素也参与计算
5.bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素。

  <div class="outer">
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
    <div class="box4"></div>
 </div>
 <style scoped>  
    .outer {
        position: absolute;  /* 创建一个BFC环境*/
        height: auto;
        background-color: #eee;
    }
    
    .box1 {
        width: 400px;
        background-color: red;
    }
    
    .box2 {
        width: 200px;
        background-color: green;
    }
    
    .box3 {
        width: 100px;
        background-color: yellow;
        float: left;
    }
    
    .box4 {
        width: 200px;
        height: 30px;
        background-color: purple;
    }

在常规文档流中,两个兄弟盒子之间的垂直距离是由他们的外边距所决定的,但不是他们的两个外边距之和,而是以较大的为准。

<div class="container">
        <div class="box"></div>
        <div class="box"></div>
  </div>
  <style scoped>
       .container {
            overflow: hidden;
            width: 100px;
            height: 100px;
            background-color: red;
        }
        
        .box1 {
            height: 20px;
            margin: 10px 0;
            background-color: green;
        }
        
        .box2 {
            height: 20px;
            margin: 20px 0;
            background-color: green;
        }
</style>

这里我门可以看到,第一个子盒子有上边距(不会发生margin穿透的问题);两个子盒子的垂直距离为20px而不是30px,因为垂直外边距会折叠,间距以较大的为准。

那么有没有方法让垂直外边距不折叠呢?答案是:有。特性的第5条就说了:bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素,同样外面的元素不会影响到BFC内的元素。所以就让box1或box2再处于另一个BFC中就行了。

左边固定宽度,右边不设宽,因此右边的宽度自适应,随浏览器窗口大小的变化而变化。

 <div class="column"></div>
   <div class="column"></div>
     <style scoped>
     .column:nth-of-type(1) {
            float: left;
            width: 200px;
            height: 300px;
            margin-right: 10px;
            background-color: red;
        }
        
        .column:nth-of-type(2) {
            overflow: hidden;/*创建bfc */
            height: 300px;
            background-color: purple;
        }
</style>


利用overflow:hidden清除浮动,浮动的盒子无法撑出处于标准文档流的父盒子的height。

猜你喜欢

转载自blog.csdn.net/smlljet/article/details/89921396