This paper introduces four methods of clearing float and tries to explain their principles. After understanding the various principles for clearing floats, you will find that many of the methods for clearing floats are essentially the same. With these principles in hand, you will be able to use them flexibly to develop different methods of clearing floats based on your situation and needs, rather than memorizing or sticking to the methods mentioned in this article.

Why clear float

Before talking about the method of clearing float, let’s first understand why to clear float, what is the purpose of clearing float, that is, to solve what kind of problem. Consider an example of a float (with the text omitted) :

<div class="topDiv">
    <div class="floatDiv">float left</div>
    <div class="textDiv">... </div> </div> <div class="bottomDiv">... </div>Copy the code

Its style is:

.topDiv {
    width: 500px;
    border: 2px solid black;
}
.floatDiv {
    width: 100px;
    height: 100px;
    border: 2px dotted red;
    color: red;
    margin: 4px;
    float: left;
}
.bottomDiv {
    width: 500px;
    height: 100px;
    margin: 5px 0;
    border: 2px dotted black;
}
.textDiv {
    color: blue;
    border: 2px solid blue;
}Copy the code

Rendering in Chrome looks like this:

The floating effect

This is definitely not the rendering we want, it may have the following problems:

  1. Text is formatted around floating elements, but we might want text (.textDiv) below the floating element, or we don’t want to.textDivThere are floating elements on both sides.
  2. Float element typesetting beyond its parent element (.topDiv), the height of the parent element collapses. Without the support of the text height, regardless of the border, the height of the parent element collapses to zero.
  3. Floating elements even affect their parent’s siblings (.bottomDivTypesetting. Because the floating element is out of the document flow,.bottomDivThe effect is ignored when calculating the position of the element, and the position of the last element continues.

To solve the first problem, we need to clear the float around the.textdiv. To solve the second problem, because the parent’s sibling position is only affected by the parent’s position, we need a way to prop up the height of the parent element by wrapping the floating element around it so that the floating element does not affect the arrangement of the elements outside the parent.

Let’s start with how to clear the float.

Two, clear float method

1. Use the Clear style

Again in the opening example, we add the following style to the element that needs to be cleared of float:

.textDiv {
    color: blue;
    border: 2px solid blue;

    clear: left;
}Copy the code

The render looks like this after the float is cleared:

Explain:

TextDiv tells the browser that there are no floating elements to my left. Please remove the floating elements to my left. However, because the float element (.floatDiv) position is already set, the browser, when calculating the position of the.textdiv, satisfies its needs by rendering the.textdiv below the float element, ensuring that there is no float element to the left. TextDiv is still in the flow of the document. It must be within the boundaries of the parent element, and the parent element can only do this by increasing its height, which is a bonus. (Clear is both, which side is not allowed to float elements, clear is the value of the corresponding direction, neither is allowed to float elements)

But what if we switch the.floatDiv and the.textDiv in HTML?

<div class="topDiv">
    <div class="textDiv">... </div> <div class="floatDiv">float left</div>
</div>
<div class="bottomDiv">... </div>Copy the code

Whether or not a clear float is applied to.textdiv, the situation looks like this:

TextDiv is positioned first, so the floating element follows. TextDiv is rendered to the left of the parent element. However, the height of the parent element is not braced and the float effect is not “internalized”, resulting in the float affecting the subsequent element layout.

It seems that there is scope for using clear to clear the float in order to boost the height of the parent element. We need more general and reliable approaches.

TextDiv (textDiv, textDiv, textDiv, textDiv, textDiv, textDiv, textDiv, textDiv, textDiv, textDiv, textDiv It doesn’t care if the float goes beyond the parent element or if the float affects subsequent element permutations. We’re just using some of the features of floats for some purpose, but that’s not a concern of clearing floats, it’s just that we’re probably more concerned with what those features can do for us than clearing floats. Clearing floats and raising the height of the parent element are two different problems. Here, it can be simply understood as the relationship between the tool and the purpose. The next two methods are both using the clear float tool to solve the problem, but not the clear float tool itself. However, we often confuse the two. Sorry, a little wordy. I didn’t make it clear.

2. Insert clear floating block-level elements before parent element closing tag

The HTML structure looks like this, with an empty block-level div inserted at the end of the floating parent element:

<div class="topDiv">
    <div class="textDiv">... </div> <div class="floatDiv">float left</div>
    <div class="blankDiv"></div>
</div>
<div class="bottomDiv">... </div>Copy the code

Application style:

.topDiv {
    width: 500px;
    border: 2px solid black;
}
.floatDiv {
    width: 100px;
    height: 100px;
    border: 2px dotted red;
    color: red;
    margin: 4px;
    float: left; } .bottomDiv { width: 500px; height: 100px; margin: 5px 0; border: 2px dotted black; } .textDiv { color: blue; border: 2px solid blue; } // blankDiv {clear: both; // or left }Copy the code

Render as follows:

TextDiv uses clear to clear the float and lift the height of the parent element. It is important to note that the element added at the end of the parent element must be a block-level element, or it cannot be raised to the height of the parent element.

3. Leverage pseudo-elements (Clearfix)

The HTML structure looks like this. For convention purposes, add a clearfix class to the.topdiv div:

<div class="topDiv clearfix">
    <div class="textDiv">... </div> <div class="floatDiv">float left</div>
</div>
<div class="bottomDiv">... </div>Copy the code

The styles apply as follows:

// omit the basic style // difference here. Clearfix :after {content:'. ';
    height: 0;
    display: block;
    clear: both;
}Copy the code

This style adds an :after pseudo-element to clearFix, the end of the parent element, to prop up the height of the parent element by clearing the float of the pseudo-element. Notice that the display value of this pseudo-element is block, that is, it is an invisible block-level element (table is used in some places because table is also a block-level element). As you probably already realize, this is just another variation of the previous method of clearing the float (adding a blank div), and the underlying logic is exactly the same. The first three methods are essentially the same.

4. Use Overflow to clear floats

First, take a visual look at how overflow clears floats.

The HTML structure is as follows:

<div class="topDiv">
    <div class="floatDiv">float left</div>
    <div class="textDiv">... </div> </div> <div class="bottomDiv">... </div>Copy the code

The styles apply as follows:

.topDiv { width: 500px; padding: 4px; border: 2px solid black; // Overflow: auto; } .floatDiv { width: 100px; height: 100px; border: 2px dotted red; color: red; margin: 4px;float: left;
}
.bottomDiv {
    width: 500px;
    height: 100px;
    margin: 5px 0;
    border: 2px dotted black;
    clear: both;
}
.textDiv {
    color: blue;
    border: 2px solid blue;
}Copy the code

Without applying the CSS identified above, the rendering results will be the same as the first image at the beginning of this article, which will look like this:

Simply add an overflow attribute with a value of auto to the parent element, and the height of the parent element is immediately inflated, enclosing the floating element. It looks like the float has been cleared, and the float will no longer affect the rendering of subsequent elements (strictly speaking, this has nothing to do with clearing the float, since no element has been cleared, regardless of the issue). Overflow values can be any valid value other than “visible”, which will raise the parent element’s height and clear the float. However, some values can have side effects, such as Scroll making the scroll bar always visible, hidden making the part outside the border invisible, and so on. So how do they float clean?

There is one concept that has been difficult to get around to explain the principle of this solution: Block Formatting Context (BFC). However, this is a very abstract concept, and it would take a lot of space to explain it clearly.

Here is the BFC definition taken from MDN:

A block formatting context is a part of a visual CSS rendering of a Web page. It is the region in which the layout of block boxes occurs and in which floats interact with each other.

Block-level formatting context is part of CSS visual rendering. It is an area that defines how the inner block boxes are rendered and how floats interact with each other.

A block formatting context (BFC) has the following characteristics:

  1. The BFC is like a barrier separating the inside and outside of the BFC. The rendering of the inside and outside areas does not affect each other. The BFC has its own set of rules for rendering internal child elements, which do not affect external rendering and are not affected by external rendering.
  2. The area of the BFC does not overlap with the outer margin area of the floating box. That is, any external floating element areas and BFC areas are distinct and cannot overlap.
  3. When calculating the height of the BFC, the height of the internal floating elements is also taken into account. In other words, even if there is only one floating element in the BFC region, the height of the BFC will not collapse, and the height is greater than or equal to that of the floating element.
  4. In an HTML structure, when the element that builds the BFC region follows a floating box, that is, a sibling of the floating box, the BFC region will first attempt to render next to the floating box, but below the floating element if the width is insufficient. [Look here]

With these points in mind, you can try to explain why overflow (value not visible) can clear floats.

When the element has overflow style set and the value is not visible, the element constructs a BFC(see the CSS documentation for definitions of BFC in which cases the element constructs a BFC). In our example, the.topdiv element constructs a BFC with overflow style set to auto. The third characteristic is that the height of the BFC should include floating elements, so the height of the.topdiv is raised to eliminate floating effects. (This answer provides an explanation as to why overflow with the value visible cannot construct a BFC.)

In fact, the function of overflow here is to build a BFC area, so that the influence of internal float can be “internalized”. If you look at the definition of a BFC, you will see that there are many ways to build a BFC region, and overflow is just one of them. Is there another way to build a BFC that can also clean up the float?

The BFC definition says that inline-block also builds BFC, so let’s try using this style:

.topDiv { width: 500px; padding: 4px; border: 2px solid black; Display: inline-block; } // All other styles are the same, omittedCopy the code

Render as follows:

Exactly the same effect! As long as we understand the principles, we can flexibly evolve different methods of cleaning up floats without having to memorize one method by heart.

Of course, it should be noted that the choice of which way to build BFC in actual projects should be analyzed on a case-by-case basis, because the role and influence of the selected style should be considered. In this example, using inline-block is exactly the same as using overflow. There are no side effects, but that doesn’t mean it will work in other projects. Even the choice of overflow values should consider their performance and impact. Of all the ways to build a BFC, the Overflow approach is probably the one with more control over external influences, which I suspect is why it is common to use Overflow to clean up floats.

At this point, I’m done with clearing floats that I want to share. In fact, if in different use scenarios, these methods are split combination (in fact, the split combination of the underlying principle), but also to achieve other forms of different methods to clear floating, the most important is to grasp the underlying principle. Knowing what is and why is the most effective way to learn.

Here is a summary of the links covered in the article:

  1. MDN Definition of BFC
  2. The CSS document defines and explains the BFC, how the BFC is created, and the internal rendering rules of the BFC
  3. Why can’t float clear when overflow is visible, while other values can, one answer on Stack Overflow
  4. How do BFC render when following floating elements

The level is limited, the article will inevitably appear inaccurate, even wrong place, looking forward to your valuable advice!