Table of Contents
Question 1. Block-level elements are all laid out in BFC, so where is this BFC?
Question 2. The role of BFC
Function 1: Use BFC to solve the margin overlap problem
作用2:解决浮动高度塌陷问题
Home Web Front-end CSS Tutorial What is BFC? Learn more about BFC and talk about its role

What is BFC? Learn more about BFC and talk about its role

Jul 08, 2022 am 11:29 AM
css bfc

What is BFC? The following article will take you to understand BFC and talk about the role of BFC. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What is BFC? Learn more about BFC and talk about its role

When I was interviewing Byte, the interviewer asked me if I knew anything about BFC. I actually read a lot of articles at the time, but I couldn’t remember them. , I feel that every article talks about the same thing, and I didn’t answer it during the interview. But after listening to teacher Wang Hongyuan’s explanation, I felt enlightened, so I wanted to share it with everyone. The following content is based on the summary of teacher Wang Hongyuan’s front-end system class. I think it is very clear. Thank you very much to teacher Wang Hongyuan

Before understanding BFC(Block Formatting Context), Let’s first take a look at what FC(Formatting Context) is:

What is BFC? Learn more about BFC and talk about its role

This passage comes from the W3C official website. We can get the following information:

  • All boxes belong to a FC

  • The layout of block-level elements belongs to a BFC. For example, div/p/h1, etc. -> The layout of the

  • inline-level elements in the BFC layout belongs to an IFC. For example, img/a/span/i -> In the IFC layout,

is simple to understand: the layout and context where block-level elements are located is BFC, and the layout and context where inline-level elements are located is IFC.

Question 1. Block-level elements are all laid out in BFC, so where is this BFC?

First, let’s take a look at the official explanation of W3C:

What is BFC? Learn more about BFC and talk about its role

According to the situation compiled on MDN, BFC will be created:

  • Root element (html)
  • Floating element (element's The float value is not none)
  • Absolutely positioned elements (the element's position is absolute or fixed)
  • Inline block elements (the element's display is inline-block)
  • Table cells (The element's display is table-cell, HTML table cell defaults to this value, table title (the element's display is table-caption, HTML table title defaults to this value) row, tbody, thead, tfoot default attributes) or inline -table)
  • Overflow calculated value (Computed) is not visible block element
  • Flexible element (display is a direct child element of the flex or inline-flex element)
  • 网Grid element (display is a direct child element of the grid or inline-grid element)
  • The element whose display value is flow-root

It can be seen that

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div></div>
    <div></div>
  </body>
</html>
Copy after login

this Box1 and box2 in the code are both laid out in the BFC of the html root element

Question 2. The role of BFC

First take a look at the official documentation on BFC Description of the function:

What is BFC? Learn more about BFC and talk about its role

The information we can get:

  • In a BFC, the box will start from the top of the containing block , will be placed one next to another in the vertical direction. Many people may be accustomed to this, but this is what BFC helps us achieve. When we set a margin-top for a box, BFC will help us parse it, and then give a top margin during the box layout

  • In a BFC, each element The left edge of will be close to the left edge of the containing block

  • In the same BFC, in the vertical direction, the margins of two adjacent boxes will overlap, and the value is The larger of the two (you can use this feature to solve the margin overlap problem)

Function 1: Use BFC to solve the margin overlap problem

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        height: 200px;
        width: 400px;
        background-color: orange;

        margin-bottom: 30px;
      }
      .box2 {
        height: 150px;
        background-color: purple;

        margin-top: 50px;
      }
    </style>
  </head>
  <body>
    <div></div>
    <div></div>
  </body>
</html>
Copy after login

At this time, box1 and box1 are both in the BFC of html, and box1 and box2 are adjacent in the vertical direction, so there will be margin overlap. Take the larger value of the two, 50px

What is BFC? Learn more about BFC and talk about its role

How to solve it? Many people may think of adding a BFC directly to box1, so directly add an overflow:hidden attribute to box1

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        height: 200px;
        width: 400px;
        background-color: orange;

        margin-bottom: 30px;

        overflow: hidden;
      }
      .box2 {
        height: 150px;
        background-color: purple;

        margin-top: 50px;
      }
    </style>
  </head>
  <body>
    <div></div>
    <div></div>
  </body>
</html>
Copy after login

What is the result?

What is BFC? Learn more about BFC and talk about its role

Found that it doesn’t work. Many people may be confused at this time. Box1 has already formed a BFC, so why does it still overlap? Let me explain to you. First of all, box1 has indeed formed a BFC at this time (it can be understood as a BFC formed inside box1), but the element box1 itself still belongs to the same BFC of html as box2, so it will still Margin overlap occurs

So we need to add a layer to box1, and then set the BFC for the outer box of box1

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      /* 给box1外层增加一个container盒子,并设置BFC */
      .container {
        overflow: hidden;
      }
      .box1 {
        height: 200px;
        width: 400px;
        background-color: orange;

        margin-bottom: 30px;
      }
      .box2 {
        height: 150px;
        background-color: purple;

        margin-top: 50px;
      }
    </style>
  </head>
  <body>
    <div>
      <div></div>
    </div>
    <div></div>
  </body>
</html>
Copy after login

At this time, box1 belongs to the BFC of the container, and box2 belongs to the BFC of the html. No Belong to the same BFC, so the margin overlap problem can be solved

What is BFC? Learn more about BFC and talk about its role

作用2:解决浮动高度塌陷问题

当我们给container里面的四个item设置浮动的时候,很明显,这几个元素都会脱离文档流,此时container不会有高度

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        background-color: orange;
      }

      .item {
        width: 400px;
        height: 200px;
        box-sizing: border-box;
        border: 1px solid #000;
        float: left;
        background-color: #f00;
      }
    </style>
  </head>
  <body>
    <div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>
Copy after login

What is BFC? Learn more about BFC and talk about its role

很多网上博主说,通过给container设置一个BFC,内部的浮动元素就会向其汇报高度,然后container就能解决浮动高度塌陷问题,这个做法是正确的,但是这个说法其实是错误,并不是因为其内部的浮动元素向其汇报了高度

事实上,想通过BFC解决高度塌陷问题需要满足两个条件:

  • 浮动元素的父元素触发BFC,形成独立的块级格式化上下文(BFC)

  • 浮动元素的父元素高度为auto

首先我们先看一段W3C的描述

What is BFC? Learn more about BFC and talk about its role

大致意思为BFC的高度是auto情况下,高度是这样计算:

  • 如果只有inline-level,是行高的顶部和底部的距离
  • 如果有block-level,是有最底层的块上边缘和最底层块盒子的下边缘之间的距离(有margin也会计算在内)
  • 如果有绝对定位元素,将被忽略(所有我们无法通过BFC解决绝对定位的高度塌陷问题)
  • 如果有浮动元素,那么会增加高度以包括这些浮动元素的下边缘(这才是BFC能解决浮动元素塌陷问题的原因,并不是因为浮动元素向上汇报了高度)

所以我们直接给container通过添加overflow属性设置BFC,则由于上述第四条4特性,container会增加高度来包括内部四个item浮动元素下边缘,所以解决了浮动塌陷问题

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        background-color: orange;
        /* 通过overflow形成BFC */
        overflow: hidden;
      }

      .item {
        width: 400px;
        height: 200px;
        box-sizing: border-box;
        border: 1px solid #000;
        float: left;
        background-color: #f00;
      }
    </style>
  </head>
  <body>
    <div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>
</html>
Copy after login

What is BFC? Learn more about BFC and talk about its role

(学习视频分享:web前端入门

The above is the detailed content of What is BFC? Learn more about BFC and talk about its role. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does placeholder mean in vue What does placeholder mean in vue May 07, 2024 am 09:57 AM

In Vue.js, the placeholder attribute specifies the placeholder text of the input element, which is displayed when the user has not entered content, provides input tips or examples, and improves form accessibility. Its usage is to set the placeholder attribute on the input element and customize the appearance using CSS. Best practices include being relevant to the input, being short and clear, avoiding default text, and considering accessibility.

What does span mean in js What does span mean in js May 06, 2024 am 11:42 AM

The span tag can add styles, attributes, or behaviors to text. It is used to: add styles, such as color and font size. Set attributes such as id, class, etc. Associated behaviors such as clicks, hovers, etc. Mark text for further processing or citation.

What does rem mean in js What does rem mean in js May 06, 2024 am 11:30 AM

REM in CSS is a relative unit relative to the font size of the root element (html). It has the following characteristics: relative to the root element font size, not affected by the parent element. When the root element's font size changes, elements using REM will adjust accordingly. Can be used with any CSS property. Advantages of using REM include: Responsiveness: Keep text readable on different devices and screen sizes. Consistency: Make sure font sizes are consistent throughout your website. Scalability: Easily change the global font size by adjusting the root element font size.

How to introduce images into vue How to introduce images into vue May 02, 2024 pm 10:48 PM

There are five ways to introduce images in Vue: through URL, require function, static file, v-bind directive and CSS background image. Dynamic images can be handled in Vue's computed properties or listeners, and bundled tools can be used to optimize image loading. Make sure the path is correct otherwise a loading error will appear.

What is the function of span tag What is the function of span tag Apr 30, 2024 pm 01:54 PM

The SPAN tag is an inline HTML tag that is used to highlight text by applying attributes such as style, color, and font size. This includes emphasizing text, grouping text, adding hover effects, and dynamically updating content. It is used by placing <span> and </span> tags around the text you want to emphasize, and is manipulated via CSS styling or JavaScript. The benefits of SPAN tags include semantic clarity, styling flexibility, and ease of maintenance.

How to wrap prompt in js How to wrap prompt in js May 01, 2024 am 06:24 AM

When using the prompt() method in JavaScript, you can achieve line breaks through the following three methods: 1. Insert the "\n" character at the position where you want to break the line; 2. Use the line break character in the prompt text; 3. Use CSS's "white" -space: pre" style forces line breaks.

What language is the browser plug-in written in? What language is the browser plug-in written in? May 08, 2024 pm 09:36 PM

Browser plug-ins are usually written in the following languages: Front-end languages: JavaScript, HTML, CSS Back-end languages: C++, Rust, WebAssembly Other languages: Python, Java

What is node in js What is node in js May 07, 2024 pm 09:06 PM

Nodes are entities in the JavaScript DOM that represent HTML elements. They represent a specific element in the page and can be used to access and manipulate that element. Common node types include element nodes, text nodes, comment nodes, and document nodes. Through DOM methods such as getElementById(), you can access nodes and operate on them, including modifying properties, adding/removing child nodes, inserting/replacing nodes, and cloning nodes. Node traversal helps navigate within the DOM structure. Nodes are useful for dynamically creating page content, event handling, animation, and data binding.

See all articles