• 【面试题】BFC的理解


    1. BFC

    Block format context(BFC)表示块级格式上下文,它是CSS中的一种布局模式,用来决定块级元素如何布局以及与其他元素的关系。BFC是一个独立的布局环境,BFC内部的元素的渲染不会影响到边界以外的元素,并且BFC中的元素会按照一定的规则进行布局。

    2. BFC的布局规则

    • BFC中的所有元素垂直排列,即每个元素从上到下排列,元素之间的垂直距离由 margin 决定,同一个 BFC 中的相邻元素之间的 margin 会发生重叠。
    • 每个块的左外边框紧贴包含块的左边框。
    • 开启了BFC的元素和浮动元素不会重叠,会挨着浮动元素显示。
    • BFC是一个独立的渲染区域,内部元素的布局不会影响外部元素的布局。
    • 计算BFC高度时,浮动子元素也参与运算。

    3. 触发BFC的方式

    • HTML根元素自动触发BFC;
    • 浮动的元素;
    • 定位的元素,position:absoluteposition:fixed
    • display:inline-block/flex/table-cell-inline-flxe
    • overflow: hidden

    4. 利用BFC清除浮动

    在元素中添加overflow:hidden;样式来清除浮动

    <style type="text/css">
        .container{
            background-color: #f1f1f1;
        }
        .left{
            float: left;
        }
        .bfc{
            overflow: hidden;
        }
    style>
    
    <div class="container bfc">
        <img src="https://profile-avatar.csdnimg.cn/default.jpg!1" class="left" style="margin-right: 10px">
        <p class="bfc">我是一段文字。。。p>
    div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    清除浮动前,图片脱离文档流
    在这里插入图片描述
    清除浮动后,图片撑开容器
    在这里插入图片描述

    5. BFC解决margin塌陷问题

    <style>
    	.top{width: 300px; height: 300px; background-color: red; margin-bottom: 100px}
    	.bottom{width: 300px; height: 300px; background-blue: red; margin-top: 200px}
    style>
    
    <body>
    	<div class = "top">div>
    	<div class = "bottom">div>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    因为top和bottom这两个div都存在于根html中,所以这两个div处于同一个BFC,它们之间会发生margin塌陷。两个块之间的margin距离为较大的那个margin值,即200px。
    在这里插入图片描述
    将其中一个块放入另一个开启了BFC的区域中之后,就可以解决margin塌陷问题。

    <style>
    	.top{width: 300px; height: 300px; background-color: red; margin-bottom: 100px}
    	.bottom{width: 300px; height: 300px; background-color: blue; margin-top: 200px}
    	.bfc{overflow: hidden}
    style>
    
    <body>
    	<div class = "bfc">
    		<div class = "top">div>
    	div>
    	<div class = "bottom">div>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这里插入图片描述

    6. 利用BFC实现双栏布局

    双栏布局:左边宽度固定,右边宽度自适应(随着屏幕的缩放而缩放)

    <style>
    	.top{background-color: red; width: 200px; height: 200px; float: left;}
    	.bottom{height: 300px; background-color: blue; overflow: hidden;}
    style>
    
    <body>
    	<div class = "top">div>
    	<div class = "bottom">div>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

  • 相关阅读:
    centos7固定IP
    CG MAGIC分享3d Max中的Corona渲染器材质如何成转换VRay材质?
    【Netty专题】用Netty手写一个远程长连接通信框架
    设计模式之备忘录模式
    前端优化 之 preload
    Oracle第二篇:删除索引提示ORA-01408:索引不存在
    电脑dll丢失应该怎么解决,dll文件丢失怎么恢复方法分享
    JVM调优-GC基本原理和调优关键分析
    一、React基础知识
    自动驾驶的关键在于安全、智能与舒适
  • 原文地址:https://blog.csdn.net/zx1041561837/article/details/127867873