0
点赞
收藏
分享

微信扫一扫

十分钟狠狠地拿下CSS中的BFC

逸省 2022-04-18 阅读 83

🤔 什么是BFC

MDN文档里的原话确实不怎么像人话,能看懂就奇了怪了。
简而言之,BFC就是一个独立的布局环境,可以认为是一个容器,在这个容器里面你随便放都不会影响到容器外的布局。而且一旦触发了BFC,那容器内部怎么布局也不受外面影响

🫣 如何触发BFC

只要元素满足下面任一条件即可触发 BFC 特性:

  • body 根元素
  • 浮动元素:float 除 none 以外的值
  • 绝对定位元素:position (absolute、fixed)
  • display 为 inline-block、table-cells、flex
  • overflow 除了 visible 以外的值 (hidden、auto、scroll)

😎 BFC特点

  • 内部的Box会在垂直方向一个接着一个地放置。
  • Box垂直方向上的距离由margin决定。属于同一个BFC的两个相邻的Box的margin会发生重叠。
  • 每个盒子的左外边框紧挨着包含块的左边框,即使浮动元素也是如此。
  • BFC的区域不会与float box重叠。
  • BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素,反之亦然。
  • 计算BFC的高度时,浮动子元素也参与计算。

🤩BFC作用

1.解决margin的重叠问题
<div class="div1"></div>
<div class="div2"></div>
.div1 {
  width: 100px;
  height: 100px;
  background-color: green;
  margin-bottom: 10px;
}

.div2 {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 20px;
}

在这里插入图片描述

<div class="wrapper">
  <div class="div1"></div>
</div>
<div class="wrapper">
<div class="div2"></div>
</div>
.wrapper{
  overflow: hidden;
}

.div1 {
  width: 100px;
  height: 100px;
  background-color: green;
  margin-bottom: 10px;
}

.div2 {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 20px;
}

在这里插入图片描述

2.解决高度塌陷问题
    <div class="container">
      <div class="item"></div>
    </div>
	.container {
        background: green;
      }
      .container .item {
        border: 1px solid red;
        width: 100px;
        height: 100px;
        /* 子元素设置浮动 */
        float: left;
      }

在这里插入图片描述
如图container高度为0,发生高度塌陷

	.container {
        background: green;
      }
      .container .item {
        border: 1px solid red;
        width: 100px;
        height: 100px;
        /* 子元素设置浮动 */
        float: left;
      }
      .clearfix::after {
        content: "";
        display: block;
        clear: both;
      }
	<div class="container clearfix">
      <div class="item"></div>
    </div>

在这里插入图片描述
或者

	.container {
        background: green;
        overflow: hidden;
      }
      .container .item {
        border: 1px solid red;
        width: 100px;
        height: 100px;
        /* 子元素设置浮动 */
        float: left;
      }
	<div class="container">
      <div class="item"></div>
    </div>
3.创建自适应两栏布局问题
	.left {
        width: 100px;
        height: 200px;
        background: red;
        float: left;
      }
      .right {
        height: 300px;
        background: blue;
        overflow: hidden;
      }
 	<div class="left"></div>
    <div class="right"></div>

在这里插入图片描述

举报

相关推荐

0 条评论