search
HomeWeb Front-endHTML TutorialAbout block-level formatting in CSS

1.BFC definition

BFC (Block formatting context) is literally translated as "block-level formatting context". It is an independent rendering area, with only Block-level boxes (block-level elements) participating. It stipulates how the internal Block-level Box is laid out and has nothing to do with the outside of this area.

In layman’s terms Said: The element that created the BFC is an independent box. The sub-elements inside will not affect the layout of the outside elements (no matter how the inside is laid out, it will not affect the outside). The BFC still belongs to the ordinary flow in the document.
##2. Generation of BFC:

Understand how BFC triggers BFC

If one of the following conditions is met, BFC can be triggered and transformed into BFC


Root element

The float attribute is not none

position

It is not static and relative

overflow

It is not visibledisplay For inline-block, table-cell, table-caption, flex, inline-flex

You will find that BFC is everywhere, you just don’t know it when you use it

3.BFC layout Rules:

What are the characteristics after transforming into BFC, as follows:

The boxes inside will be placed one after another in the vertical direction.

The vertical distance of the Box is determined by margin. The margins of two adjacent boxes belonging to the same BFC will overlap

The left side of the margin box of each element is in contact with the left side of the containing block border box (for left-to-right formatting, otherwise on the contrary). This is true even if there is float.

The BFC area will not overlap with the float box.

BFC is an isolated independent container on the page. The sub-elements inside the container will not affect the elements outside. And vice versa.

When calculating the height of BFC, floating elements also participate in the calculation

4.BFC function:

Use it to come boby

1.Prevent

Margin

Overlapbfc causes the margins of child elements in the same bfc to overlap (the vertical distance of the Box is determined by the margin. The margins of two adjacent Boxes belonging to the same BFC will occur Overlap)

Problem: As you can see from the picture, there is only a 20px margin between String1 and String2. Logically speaking, it should be 40px, but this causes their margins to overlap in bfc


Code:

<style>.container1{
        /* 通过overflow:hidden可以创建bfc */
        overflow: hidden;
        background-color: red;
        width: 300px;
    }
    .sub1{
        margin: 20px 0px;
        background-color: #dea;
    }</style><div class="container1">
        <div class="sub1">String1</div>
        <div class="sub1">String2</div></div>

Solution: We can wrap a container outside the div and trigger the container to generate a BFC. Then the two divs do not belong to the same BFC, and margin overlap will not occur.


Code:

<style>
    .newbfc{
            overflow: hidden;
    }</style><div class="container1">
        <div class="sub1">String1</div>
        <div class="newbfc"><div class="sub1">String2</div></div></div>

2.

Clear float

:Problem: When the child elements of an element are all floated Afterwards, there will be a height collapse phenomenon, that is, the height of the parent container will not be stretched


Code:

<style>
    .pre2{
        width: 200px;
        border: 2px solid red;
    }
    .float1,.float2{
        width: 100px;
        height: 100px;
        float: left;
    }
    .float1{
        background-color: #dee;
    }
    .float2{
        background-color: #dcc;
    }</style><div class="pre2">
        <div class="float1"></div>
        <div class="float2"></div></div>

Solution:

bfc rules: When calculating the height of BFC, floating elements also participate in the calculation, so as long as the parent container is set to bfc, the child elements can be included:

This container will contain floating child elements, and its height will expand can contain its child elements, which, in this BFC, will flow back into the page's regular document flow.

.pre2{
        width: 200px;
        border: 2px solid red;
        /* 设置overflow*/
        overflow:hidden;
    }

3. Solve the layout: prevent text wrapping


Code:

<style>.container2{
        overflow: hidden;
        width: 200px;
    }
    .box{
        float: left;
        width: 100px;
        height: 30px;
        background-color: #daa;
    }</style><div class="container2">
        <div class="box"></div>
        <p style="background-color: #eea">sdfadsfdff fffffffds fsfffff sfd  fsdsdfsdf fffffff</p></div>

This p element does not move, but it appears below the floated element. The line boxes (referring to text lines) of the p element are shifted. Here the horizontal shrinkage of line boxes provides space for floating elements.

BFC rules: The left side of the margin box of each element touches the left side of the containing block border box (for left-to-right formatting, otherwise the opposite). This is true even if there is float.

To solve this problem, just add overflow: hidden to the p element to make it a new bfc.

I believe you have mastered the method after reading these cases. Please pay attention to php for more exciting things. Other related articles on the Chinese website!

Related reading:

What are the commonly used attributes for dividing frames and windows in HTML?


What are the references to CSS in HTML? Method


What are the methods of removing borders and borderless iframes

The above is the detailed content of About block-level formatting 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
Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.