详解BFC

1.BFC概念

BFC(Block Formatting Contexts)块级格式化上下文,它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。

具有BFC特性的容器会隔离外界的一切,无论外面的元素如何变化都始终不会影响内部。

2.BFC触发条件

  • float的值不是none
  • position的值不是static或是relative
  • display的值是inline-block、table-cell、flex、table-caption或者inline-flex
  • overflow的值不是默认值visible

3.BFC典型应用

  • 解决margin传递

比如给子元素设置margin-top,但是父元素也会受到影响。如果启动BFC就能够很好地解决该问题,使得无论内部元素如何改变都不会影响外部

<!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>
    .main{
      width: 200px;
      height: 200px;
      background-color: aqua;
      /* 触发Bfc */
      float: left; 
    }
    .main div{
      width: 100px;
      height: 100px;
      background-color: salmon;
      margin-top: 30px;
    }
  </style>
</head>
<body>
  <div class="main">
    <div></div>
  </div>
</body>
</html>
  •  解决margin折叠

两个div元素要各自启动BFC

<!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>
   section{
    overflow: hidden;
   }
   .div1{
    width: 100px;
    height: 100px;
    background-color: aqua;
    margin-bottom: 20px;
   }
   .div2{
    width: 100px;
    height: 200px;
    background-color: pink;
    margin-top: 20px;
   }
  </style>
</head>
<body>
  <section>
    <div class="div1"></div>
  </section>
  <section>
    <div class="div2"></div>
  </section>
</body>
</html>
  • 解决父容器高度塌陷问题

 子元素设置浮动后,父容器容易出现高度塌陷的问题。

<!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>
   .main{
    /* 触发BFC */
    width: 100px;
    overflow: hidden;
    border: 1px solid black;
   }
   .main div {
    width: 100px;
    height: 100px;
    float: left;
    background-color: aqua;
   }
  </style>
</head>
<body>
  <div class="main">
    <div></div>
  </div>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值