preface

It’s common to be asked in an interview, “How do I clear the float?” “, “Why can Overflow: Hidden clear float?” And so on. While these questions can be found in a variety of interview essay essays, the textbook question and answer is certainly not the goal, rather than memorizing the answer to the core principle of block format Context (BFC).

This article is mainly to thoroughly analyze the principle of BFC, summarize the usage of BFC in classic scenarios, and finally practice analysis to solve the problems often encountered in layout.

This article is originally from dino notes, reprinted by 😁

I. Role of BFC

  • Clear float: THE BFC contains everything inside the element that created it (including float elements)
  • Margin folding: Resolves margin folding between adjacent elements in the same BFC container
  • Left and right text layout: using floating elements to generate BFC and BFC does not overwrite each other to achieve left and right text layout

The above functions of BFC can be used as a test. Think about how to achieve it. There will be explanations on the principle and implementation later in this paper

Ii. How to generate BFC

The name of the How to produce note
HTML root element The HTML element is itself a BFC element Just remember, the body element is not a BFC
The floating element The float property of the element is not None The commonly used
Absolute location element The position attribute is absolute or fixed The commonly used
Inline block elements The display attribute is inline-block The commonly used
Table element The default display attribute of a table element is BFC So are table cells and table titles
The elastic element The display attribute is a direct child of the flex or inline-flex element Very important (Flex layout used)
Grid elements The display attribute is a direct child of the grid or inline-grid element New features are used sparingly
Multiple columns container The column-count or column-width of the element is not auto, including column-count 1 New features are used sparingly
Overflow attributes Element whose overflow property value is not visible Commonly used oveFLfow: visible
The display properties Element whose display attribute value is flow-root, flow-root: the value of a new display attribute that creates a BFC without side effects With less
Contain attributes Contain elements that contain layout, Content, and paint With less

In a word: Anything that leaves the document stream can produce a BFC

Iii. Principle of BFC

Three ways to locate documents

Before we get into the BFC, let’s look at three ways that AN HTML document can be positioned

Normal flow

In a normal stream, elements are laid out from top to bottom according to their sequence position in THE HTML. In this process, inline elements are arranged horizontally until a row is filled and then a line is wrapped. Block-level elements are rendered as a complete new row. That is, the position of an element in a normal stream is determined by its position in the HTML document.

floating

In float positioning, elements appear in their normal stream position and then drift as far to the left or right as possible depending on the direction of the float, similar to text wrap in print typography.

Absolute positioning

In absolute positioning, the element is completely detached from the normal flow, so the absolute positioning element does not affect its sibling element, and the exact position of the element is determined by the absolute positioning coordinates.

Why BFC works

In fact, BFC is a common flow of the above three layouts. The BFC produces a separate container, and the elements inside the container do not affect the layout of the external elements. The external normal flow looks like any other normal flow elements.


BFC considerations

The block formatting context is important for both locating floats and clearing floats. Float location and clear float are only applied to elements in the same BFC. Floats do not affect the layout of elements in other BFC, and clearing floats only clears floats of elements before it in the same BFC. Margin folding also occurs only between block-level elements belonging to the same BFC.

4. Common usage of BFC

To better understand BFC, let’s take a look at the following common uses.

🌰 Clear floating to prevent height collapse

According to the above three positioning methods, floating elements will be separated from the ordinary document flow, resulting in the height calculation of external elements does not include the height of the floating element itself, resulting in height collapse.

Height of collapse
<div class="container">
  <div class="box box1"></div>
</div>
Copy the code
.box { width: 20px; height: 50px; float: left; // Create a BFC border: 4px solid green; }Copy the code

Using one of the above methods to generate BFC elements to generate BFC outer elements can prevent high collapse of elements.

.container { overflow: hidden; // The outer container generates BFC}Copy the code
Repair height collapse

🌰 handles margin folding

In normal document flow, the margins of elements (non-BFC elements) collapse automatically, resulting in the following phenomenon.

Margin folding
<div class="container">
  <div class="box box1 m20"></div>
  <div class="box box2 m20"></div>
</div>
Copy the code
.m20 {
  margin: 20px;
}
.box {
  border: 1px solid green;
}
Copy the code

This is an HTML feature and not a bug, but we prefer that margins do not fold, by taking advantage of the fact that margins between BFC elements do not fold.

<div class="container">
  <div class="box box1 m20"></div>
  <div class="box box2 m20"></div>
</div>
Copy the code
.m20 { margin: 20px; } .box { overflow: hidden; // Make both boxes BFC elements border: 4px solid green; }Copy the code

Make two boxes to form BFC or wrap the box with two BFC respectively, and then the margins between the two BFC formed will not fold. The effect after repair is shown in the figure below.

Fix margin folding

Five, expand

The existence of block-level formatting context BFC corresponds to the existence of inline formatting context IFC, grid formatting context GFC and adaptive formatting context FFC, all of which can be collectively referred to as formatting context.

IFC

For inline formatting context, the height of the IFC’s line box is calculated from the actual height of the element inside the line, regardless of the vertical padding and margin.

IFC schematic

What happens when you insert a block-level element inside an inline element? Each of the inline elements before and after insertion forms an IFC, which is then laid out as a normal document flow, as shown below.

Insert block-level elements into inline elements

GFC

Grid layout formatting context (display: grid)

FFC

Adaptive formatting context (display: flex)

Analysis of common problems

🍓 Why can overflow: Hidden clear float?

Overflow: Hidden causes the outer element to produce a BFC, and the height calculation of the BFC contains its inner floating element to clear the floating effect

<div style="border: 5px solid #6EBD91; overflow: hidden;">
  <div style="float: left; border: 5px solid #F4D491;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, maxime fuga assumenda excepturi, exercitationem rerum quae voluptates sunt perspiciatis cupiditate sed itaque officia, placeat minus iure quod expedita earum nam.Eum aliquam totam iure mollitia deserunt, minus repellendus. Harum ullam tenetur, impedit aliquam nobis ut dignissimos eligendi, expedita illum iste esse odio ab quos explicabo, odit architecto. Tempora, hic facilis?</div>
</div>
Copy the code

The effect is as follows:

Remove the floating

The analysis process

The outer overflow: hidden element generates a BFC, and the float: left element itself generates a BFC. The outer BFC calculates the size of the inner BFC.

The results of

🍓 How to implement the clearfix float commonly used?

Clearfix ::after {content: ""; display: block; height: 0; clear: both; } // Compatible ie6.clearfix {zoom: 1; }Copy the code

The. Clearfix class is bound to the outer non-floating element, and the clear: both attribute ensures that the outer element contains the inner floating element for height calculations.

Using ClearFix to clear floating elements does not itself produce a BFC, relying on the CLEAR property of the CSS. That is, if the element produces BFC with no other attributes, it is positioned as a normal document flow, and the vertical margins are still folded.

🍓 How to implement two-column adaptive layout?

Instead of using layout components in the UI framework, use float: left + fixed left width + right column margin-left

<div>
  <img style="float: left; width: 140px;" src="https://tva1.sinaimg.cn/large/00831rSTly1gcel7v9ji4j3041041wec.jpg" alt="logo">
  <div style="margin-left: 150px;">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos eligendi numquam nihil excepturi sint reiciendis iusto maiores nostrum fugiat harum?</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, perspiciatis magnam consectetur corrupti suscipit a ratione sunt commodi beatae ad!</p>
  </div>
</div>
Copy the code

The realization effect is shown as follows:

Left picture right text layout

Process analysis

Using float: left on the left side produces a BFC element that performs normal stream positioning along with the right block-level element div; Since the two elements are not overwritten before they are positioned in normal flow, the effect can be achieved without fixing the width of the left element and the block-level element to the margin-left (the width is given to control the fixed size of the left).


🍓 What is the effect of using block-level elements in inline elements?

Inserting block-level elements in an inline element creates an anonymous block before and after the inserted block-level element, and the inserted block is positioned in a normal stream


🍓 What happens when you insert a floating element in an inline element?

The inline element uses display: inline-block to produce an IFC whose internal float is floated internally and the entire IFC is then positioned externally as a block-level element for document flow

<span style="display: inline-block; background-color: #6EBD91;">
  Lorem ipsum dolor sit amet.
  <span style="float: left; background-color: chocolate;">Lorem, ipsum.</span>
  <div style="background-color: #F4D491;">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Repellat labore, ipsa quo possimus mollitia, officiis quia provident inventore placeat nulla, rem velit ratione ducimus. Facilis eos repudiandae debitis quam voluptatem.</div>
  Lorem ipsum dolor sit amet consectetur.
</span>
Copy the code

The effect is as follows:

The effect

The above effects can be previewed online

Refer to the article

  • MDN- Formatting context
  • MDN-clear
  • Gihtub – An introduction to BFC and its applications
  • Zhihu Column -10 minutes to understand BFC principles

Write in the last

Now that I see this, I might as well click a “like” to encourage the author

Author’s blog: blog.lessing.online/

Author: github github.com/johniexu