BFC理解与应用

本文深入解析了块格式化上下文(BFC)的概念,详细介绍了BFC的触发条件及其在解决网页布局问题中的应用场景,如防止父元素塌陷、解决margin重叠等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是BFC?

块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域

个人理解就是BFC的触发会让盒子形成封闭空间与外部元素布局互不影响。

BFC触发条件:

  1. html根元素(其实BFC就是构造了一个和根元素类似的盒子)
  2. 浮动元素:float 除 none 以外的值
  3. 绝对定位元素:position (absolute、fixed)
  4. display 为 inline-block、table-cells、flex
  5. overflow 除了 visible 以外的值 (hidden、auto、scroll)

注释:还有其他的触发方式,只是兼容性不好,这里不提出详情

触发条件的对比:

  1. float会导致盒子浮动,对盒子兄弟有影响;
  2. 绝对定位,会脱离文档流,盒子会改变原生的一些样式;
  3. dispaly也会改变盒子的原有特性;
  4. overflow比较好,如果盒子宽高没有定死,不会出现裁剪的情况(建议使用的方式)

应用场景:

  • 子元素浮动引起父元素塌陷
<style>
    body {
        padding: 20px;
    }
    .father {
        border: 1px solid;
    }
    .box {
        background-color: red;
        height: 50px;
        width: 50px;
        float: left;
    }
</style>
<body>
    <div class="father">
        <div class="box"></div>
        我是有内容的
    </div>
</body>

解决办法:

1.在father元素上设置overflow: hidden;父元素还是占文档流的一行,表现为块级元素

2.在father元素上设置position: absolute;父元素由于脱离文档流,表现为一个行内元素

 

  • 父子元素margin区域重合
<style>
    body {
        padding: 20px;
    }
    .father {
        /* border: 1px solid; */很特殊,也会是父子margin的分离
        background-color: yellow;
        height: 400px;
    
    .box {
        background-color: red;
        height: 50px;
        width: 50px;
        margin-top: 10px;
    }
</style>
<body>
    <div class="father">
        <div class="box"></div>
    </div>
</body>

解决办法:

1.建设使用overflow: hidden;触发BFC

2.给父元素设置border也能分离父子元素的magin

  • 兄弟元素margin重合取大的
<style>
    body {
        padding: 20px;
    }
    .father {
        border: 1px solid;
        /* background-color: yellow; */
        height: 400px;
    }
    .box {
        background-color: red;
        height: 50px;
        width: 50px;
        margin-bottom: 50px;
    }
    .box1 {
        background-color: yellow;
        height: 50px;
        width: 50px;
        margin-top: 10px;
    }
</style>
<body>
    <div class="father">
        <div class="box"></div>
        <div class="box1"></div>
    </div>
</body>

解决办法:

1在一个div外面套一个div然后触发该div的BFC

2直接在后面的子元素设置position:absolute; 

  • 自适应布局,左右与上下布局中的铺满解决方案中的应用

具体实现细节

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值