BFC(块级格式化上下文)

BFC(Block Fomatting Context) 块级格式化上下文

  • 形成独立的渲染区域,内部元素的渲染不会影响外界
  • 作用:
    1. 消除外边距重叠现象(同一个BFC的两个相邻Box的上下margin会发生重叠)
    2. 清除浮动(计算BFC的高度时,浮动元素也参与计算)
    3. 阻止元素被浮动元素覆盖
    4. 阻止子元素设置margin-top,父元素也一起掉下来
    <style>
      .box1 {
        margin-top: 300px;
        height: 600px;
        background-color: rebeccapurple;
      }
    </style>
    <div class="father">
      <div class="box1"></div>
    </div>
    
    1. 自适应两栏布局(左边固定,右边自适应)
  • 触发BFC:
    1. float不为none
    2. position为absolute或者fixed
    3. overflow不为visible
    4. flex元素
    5. inline-block元素
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      /* 方案一 */
      html,
      body {
        padding: 0;
        margin: 0;
        height: 100%;
      }
      .box1 {
        float: left;
        width: 300px;
        height: 100%;
        background-color: green;
      }
      .box2 {
        float: left;
        width: calc(100% - 300px);
        height: 100%;
        background-color: blue;
      }

      /* 方案二: flex布局 */
      /* html {
        padding: 0;
        margin: 0;
        height: 100%;
      }
      body {
        padding: 0;
        margin: 0;
        height: 100%;
        display: flex;
        flex-direction: row;
      }
      .box1 {
        width: 300px;
        height: 100%;
        background-color: green;
      }

      .box2 {
        height: 100%;
        flex-grow: 1;
        background-color: blue;
      } */

      /* 方案三 触发bfc,但是宽度默认自适应*/
      /* html,
      body {
        padding: 0;
        margin: 0;
        height: 100%;
      }

      .box1 {
        float: left;
        width: 300px;
        height: 100%;
        background-color: green;
      }

      .box2 {
        overflow: hidden;
        height: 100%;
        background-color: blue;
      } */
    </style>
  </head>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
  </body>
</html>

清除浮动

  1. overflow:hidden;
  2. 内墙法/外墙法
  3. 伪元素清除
选择器::after{
   content:'';
   height:0;
   clear:both;
   display:none;
   visibility:none;
   overflow:hidden
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值