Block Formatting Context(BFC)

创建BFC的好处:

1.包含内部的浮动元素

2.排除外部的浮动元素

3.阻止外边距margin合并

 

推荐使用display:flow-root;来创建BFC

!!!下面的demo引自MDN

 

包含内部的浮动元素

<section>
    <div class="box" style="display:flow-root">
        <div class="float">I am a floated box!I am a floated box!I am a floated box!I am a floated box!I am a floated box!I am a floated box!I am a floated box!I am a floated box!</div>
        <p>some other text</p>
    </div>
</section>
section {
    height:150px;
}
.box {
    background-color: aliceblue;
    border: 5px solid steelblue;  
}
.float {
    float: left;
    width: 200px;
    background-color: rgba(255, 255, 255, .5);
    border:1px solid black;
    padding: 10px;
}

 

排除外部的浮动元素

<section>
  <div class="float">Try to resize this outer float</div>
  <div class="box"><p>Normal</p></div>
</section>
<section>
  <div class="float">Try to resize this outer float</div>
  <div class="box" style="display:flow-root"><p><code>display:flow-root</code><p></div>
</section>
section {
    height:150px;
}
.box {   
    background-color: rgb(224, 206, 247);   
    border: 5px solid rebeccapurple; 
} 
.box[style] {   
    background-color: aliceblue;   
    border: 5px solid steelblue;   
} 
.float {   
    float: left;
    overflow: hidden; /* required by resize:both */
    resize: both;
    margin-right:25px;
    width: 200px;   
    height: 100px;   
    background-color: rgba(255, 255, 255, .75);   
    border: 1px solid black;   
    padding: 10px; 
}

 

阻止外边距margin合并

<div class="outer-blue">
  <div class="blue"></div>
</div>
<div class="red-inner">red inner</div>
.blue, .red-inner {
  height: 50px;
  margin: 10px 0;
}

.outer-blue {
  background: blue;
  display: flow-root;
}

.red-inner {
  background: red;
}

 

posted @ 2020-11-29 20:11  xqcokid  阅读(120)  评论(0编辑  收藏  举报