前端面试知识点(五)--- BFC的创建和作用

如何创建BFC

1、float的值不是none。
2、position的值不是static或者relative。
3、display的值是inline-block、table-cell、flex、table-caption或者inline-flex
4、overflow的值不是visible

BFC的作用

  1. 利用BFC避免margin重叠。
    一起来看一个例子:

    <style>
        *{
            margin: 0;
            padding: 0;
        }
        p {
            color: #f55;
            background: yellow;
            width: 200px;
            line-height: 100px;
            text-align:center;
            margin: 30px;
        }
    </style>
    <body>
        <p>看看我的 margin是多少</p>
        <p>看看我的 margin是多少</p>
    </body>
    

    页面效果如下:在这里插入图片描述
    我们会发现,p标签垂直方向的margin重合了,因为属于同一个BFC的两个相邻的Box会发生margin重叠
    解决方法:我们可以让把第二个p用div包起来,然后激活它使其成为一个BFC

    <style>
        *{
            margin: 0;
            padding: 0;
        }
        p {
            color: #f55;
            background: yellow;
            width: 200px;
            line-height: 100px;
            text-align:center;
            margin: 30px;
        }
        div{
            overflow: hidden;
        }
    </style>
    <body>
        <p>看看我的 margin是多少</p>
        <div>
            <p>看看我的 margin是多少</p>
        </div>
    </body>
    

    页面效果如下:在这里插入图片描述

  2. 解决兄弟盒子间因浮动产生的遮盖问题

    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body {
            width: 100%;
            position: relative;
        }
        .left {
            width: 100px;
            height: 150px;
            float: left;
            background: rgb(139, 214, 78);
            font-size: 20px;
        }
        .right {
            height: 300px;
            background: rgb(170, 54, 236);
            font-size: 40px;
        }
    </style>
    <body>
        <div class="left">LEFT</div>
        <div class="right">RIGHT</div>
    </body>
    

    页面效果如下:在这里插入图片描述
    我们发现当左边的盒子设置浮动后,右边的盒子被遮盖了,为了解决这个问题,我们让right盒子成为一个单独的BFC

    .right {
    	overflow: hidden; //创建BFC
        height: 300px;
        background: rgb(170, 54, 236);
        font-size: 40px;
    }
    

    页面效果如下:在这里插入图片描述

  3. 解决父元素因子元素浮动产生的高度塌陷问题(清除浮动)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值