search
HomeWeb Front-endCSS TutorialThe magic of BFC in CSS.

This time I will bring you the magic of BFC in CSS. , what are the precautions when using BFC in CSS? The following is a practical case, let’s take a look.

When writing styles, we often add a style or modify a certain attribute to achieve our expectations.

And BFC is hidden in it. When you modify the style, you can trigger it accidentally without realizing it, so you don't realize the magic of BFC.

1. What is BFC (Block Formatting Context)

When writing CSS styles, to set css on an element, we first need to know whether the element is a block-level element or Inline elements, and BFC is used to format block-level boxes.

Formatting Context: refers to a rendering area in the page and has a set of rendering rules, which determines how its sub-elements are positioned, as well as their interaction and interaction with other elements.

BFC definition: Block-level formatting context, which refers to an independent block-level rendering area, only Block-level Box participates. This area has a set of rendering rules to constrain the layout of block-level boxes, and is consistent with Not relevant outside the area.

2. Generation of BFC

We mentioned that BFC is a rendering area, so where is this rendering area and what is its specific size? These are determined by the elements that generate the BFC.

Elements that meet one of the following CSS declarations will generate a BFC:

1. The root element or other elements containing it

2. The value of float is not none;

3. The value of overflow is not visible;

4. The value of position is not static;

5. The value of display is inline- block, table-cell, table-caption;

6, flex boxes (display of element: flex or inline-flex);

Note: Some people also think that display: table can generate BFC, I think the main reason is that table will generate an anonymous table-cell by default, and it is this anonymous table-cell that generates BFC.

3. The layout rules of BFC

are simply summarized as follows:

1. The internal elements will be arranged one after another in the vertical direction. You can Understood as a regular flow in BFC

2. The vertical distance of elements is determined by margin, that is, the margins of two adjacent boxes belonging to the same BFC may overlap

3 , the left margin of each element is in contact with the left boundary of the containing block (from left to right, otherwise the opposite), even if there is a float, which means that the child elements in BFC will not exceed its Containing blocks

4. The BFC area will not overlap with the float element area

5. When calculating the height of BFC, floating sub-elements also participate in the calculation

6. BFC is An isolated independent container on the page. The child elements inside the container will not affect the elements outside and vice versa

4. Application of BFC

said So much, then what is the use of our BFC? Below we use several examples to solve some problems:

Example 1. Solving the margin overlap problem

Friends who play CSS all know margin collapse, that is, adjacent vertical elements have margins set at the same time. Afterwards, the actual margin value will collapse to the larger value.

The basic principle is that they are in the same BFC, which conforms to the rule that "the margins of two adjacent elements belonging to the same BFC will overlap".

margin overlapping phenomenon

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>margin重叠现象</title>
    <style>
        *{margin: 0;padding: 0;}
        .box p {
            margin: 20px 0px;
            background-color: skyblue;
        }
    </style>


    <p>
        </p><p>Lorem ipsum dolor sit.</p>
        <p>Lorem ipsum dolor sit.</p>
        <p>Lorem ipsum dolor sit.</p>
    

##Through the experimental results, we found that the upper and lower margins overlap.

We can wrap a container around one of the elements and trigger the container to generate a BFC. Then the two elements belong to different BFCs, and margin overlap will not occur.

We make the following modifications:

<p>
    </p><p>Lorem ipsum dolor sit.</p>
    <p>
        </p><p>Lorem ipsum dolor sit.</p>
    
    <p>Lorem ipsum dolor sit.</p>

我们使用overflow:hidden;生成了一个BFC,成功解决了margin重叠问题。

实例2、解决浮动问题

我们知道给父元素设置overflow:hidden可以清除子元素的浮动,但往往都不知道原理是什么。

其实这就是应用了BFC的原理:当在父元素中设置overflow:hidden时就会触发BFC,所以他内部的元素就不会影响外面的布局,BFC就把浮动的子元素高度当做了自己内部的高度去处理溢出,所以外面看起来是清除了浮动。

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>BFC浮动问题</title>
    <style>
        .one {
            /* 文档流 里面的文字标签将父元素撑起来 */
            background-color: pink;
        }
        .two {
            float: left;
        }
    </style>


    <!-- 文档流 从上到下,当遇到float、position:absolute时,会离开文档流 -->
    <p>
    </p><p>Hello World!</p>
    
    你好世界!

我们做如下修改:

.one {
        background-color: pink;
        overflow: hidden;
    }

对比发现,当我们一个元素设置成为BFC之后,计算BFC元素高度的时候,浮动元素也参与了计算。

实例3、解决侵占浮动元素的问题

我们知道浮动元素会脱离文档流,然后浮盖在文档流元素上。

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>BFC侵占浮动元素的问题</title>
    <style>
        .box1 {
            float: left;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        .box2 {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>


    <p>box1</p>
    <p>box2</p>

当一个元素浮动,另一个元素不浮动时,浮动元素因为脱离文档流就会盖在不浮动的元素上。

我们做如下修改:

.box2 {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        overflow: hidden;
    }

或如下修改:

.box2 {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        /* overflow: hidden; */
        float: left;
    }

我们为非浮动元素建立BFC环境,根据BFC的不与float box重叠的规则,解决了侵占元素问题。

这一特性,我认为还是很有用的,特别是应用在两栏布局上,对比我们常规为非浮动元素或非定位元素设置margin来挤开的方法,其优点在于不需要去知道浮动或定位元素的宽度。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

css3的动画序列animation

CSS怪异盒模型和标准盒模型如何使用

The above is the detailed content of The magic of BFC in CSS.. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Static First: Pre-Generated JAMstack Sites with Serverless Rendering as a FallbackStatic First: Pre-Generated JAMstack Sites with Serverless Rendering as a FallbackApr 16, 2025 am 11:06 AM

You might be seeing the term JAMstack popping up more and more frequently. I’ve been a fan of it as an approach for some time.

CSS-Tricks Chronicle XXXVICSS-Tricks Chronicle XXXVIApr 16, 2025 am 10:58 AM

This is one of these little roundups of things going on with myself, this site, and the other sites that are part of the CSS-Tricks family.

Weekly Platform News: Emoji String Length, Issues with Rounded Buttons, Bundled ExchangesWeekly Platform News: Emoji String Length, Issues with Rounded Buttons, Bundled ExchangesApr 16, 2025 am 10:46 AM

In this week's roundup, the string length of two emojis is not always equal, something to consider before making that rounded button, and we may have a new

Meeting GraphQL at a Cocktail MixerMeeting GraphQL at a Cocktail MixerApr 16, 2025 am 10:43 AM

GraphQL and REST are two specifications used when building APIs for websites to use. REST defines a series of unique identifiers (URLs) that applications use

Introducing Sass ModulesIntroducing Sass ModulesApr 16, 2025 am 10:42 AM

Sass just launched a major new feature you might recognize from other languages: a module system. This is a big step forward for @import. one of the most-used

How I Learned to Stop Worrying and Love Git HooksHow I Learned to Stop Worrying and Love Git HooksApr 16, 2025 am 10:41 AM

The merits of Git as a version control system are difficult to contest, but while Git will do a superb job in keeping track of the commits you and your

A Proof of Concept for Making Sass FasterA Proof of Concept for Making Sass FasterApr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Demonstrating Reusable React Components in a FormDemonstrating Reusable React Components in a FormApr 16, 2025 am 10:36 AM

Components are the building blocks of React applications. It’s almost impossible to build a React application and not make use of components. It’s widespread

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),