什么是BFC

3 篇文章 0 订阅

MDN的解释是BFC
在这里插入图片描述
简单来说就是,BFC 是一个完全独立的空间,让空间里的子元素不会影响到外部的布局, BFC可以看做是一个css元素属性来使用

这里简单列举几个触发BFC使用的CSS属性

overflow: hidden
display: inline-block
position: absolute
position: fixed
display: table-cell
display: flex

案例 清除浮动

 <style>
        .content {
            background-color: pink;
        }
        .box1 {
            width: 200px;
            height: 200px;
            background-color: green;
        }
        .box2 {
            width: 200px;
            height: 200px;
            background-color: orange;
        }
    </style>
    <div class="content">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>

在这里插入图片描述

当.box1 .box2 设置为float:left 之后,两个盒子就会变成浮动流,父盒子无法被撑开,接下来粉色的背景色就看不见了,父盒子剩下边框黑线
在这里插入图片描述

这时候 只要给父盒子触发BFC,就可以处理父盒子因为子元素浮动无法撑开的问题
给父元素可以设置为 display:inline-block; 这样清除浮动,本质也是触发了BFC,
在这里插入图片描述

案例二 外边距合并

    <style>
        .box1 {
            width: 200px;
            height: 200px;
            margin-bottom: 20px;
            background-color: green;
        }

        .box2 {
            /* position: absolute; */
            /* display: inline-block; */
            width: 200px;
            height: 200px;
            margin-top: 20px;
            background-color: orange;
        }
    </style>
    <div class="content">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>

在这里插入图片描述

我们可以给第二个盒子触发BFC,成为一个独立的空间,这两两个盒子之间的外边距距离就能是40px了
可以给.box2 设置为
/* position: absolute; /
/
display: inline-block; */ 都可以触发box2的BFC
在这里插入图片描述

    <style>
        .box1 {
            width: 200px;
            height: 200px;
            margin-bottom: 20px;
            background-color: green;
        }

        .box2 {
            /* position: absolute; */
            display: inline-block;
            width: 200px;
            height: 200px;
            margin-top: 20px;
            background-color: orange;
        }
    </style>
    <div class="content">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值