Why does CSS want to clear float (float)? What is the principle of clear float?

Source: Internet
Author: User
css Float (float), a property that we love and hate. Love, because through the floating, we can easily layout; hate, floating after the left too many problems need to be solved, especially ie6-7 the following no special description refers to the Windows platform of IE floating (float), a We are love and hate properties. Love, because through the floating, we can easily layout; hate, floating after the left too many problems need to be resolved, especially ie6-7 (the following no special instructions refer to the Windows platform IE browser). Perhaps a lot of people have this question, where does the float come from? Why does CSS need to clear floating? What is the principle of clear float? This article will take a step-by-step deep analysis of the mystery, so that floating use more handy.
first, clear floating or closed float (enclosing float or clearing float)?
Many people have been accustomed to call it clear float, which I used to call, but not exactly. We should use a rigorous approach to the code, but also better to help us understand the beginning of the three questions.
1) Clear float: Clears the corresponding word is clear, corresponding to the property in the CSS is Clear:left | Right | both | None
2) Closed float: The more precise implication is that the floating element is closed, thereby reducing the impact of the float.
The difference between the two see the elegant Demo
Through the above examples found that in fact we want to achieve the effect is more precisely closed floating, rather than simply clear floating, set on the footer Clear:both clear floating does not solve the problem of warp height collapse.
Conclusion: It is more rigorous to use the closed floating ratio to clear the float, so the following article is called: Closed float.
Second, why should the float be cleared?
To answer this question, we have to first talk about the positioning mechanism in CSS: normal flow, floating, absolute positioning (where "position:fixed" is a subclass of "Position:absolute").
1) Normal flow: Many people or articles called document flow or ordinary document flow, in fact, there is no such word in the standard. If you translate the document flow literal to English is document flow, but there is only another word in the standard, called the normal flow, or it is called the regular flow. But it seems that people are more accustomed to the name of the flow of documents, because many Chinese translation of the book is so. For example, "CSS mastery", the English original book from the beginning to the end there is only normal flow normal flow (normal stream) This word, has never seen document flow
2) Floating: The floating box can move left and right until its outer edge encounters the edge of the containing box or another floating box. A floating box does not belong to a normal stream in the document, and when an element floats, it does not affect the layout of the block-level box but only the arrangement of the inline box (usually text), and the normal flow in the document behaves as if the float box does not exist, and when the float box height exceeds the containing box, the Include box does not Auto stretch to close floating elements ("height collapse" phenomenon). As the name implies, is floating on the ordinary stream, like a cloud, but only left and right floating.
It is precisely because of this characteristic of the float that the element that belongs to the normal flow is floating, and the inside of the box contains no other ordinary flow elements, it shows a height of 0 (height collapse). In the actual layout, this is often not what we want, so we need to close the floating element so that its inclusion box shows its normal height.
Absolute positioning is not much to say, not within the scope of this article, tell.
Third, the principle of clear floating--understand haslayout and Block formatting contexts
Let's take a look at the various ways to clean up the float: (the most complete CSS clearfix to clear the floating method)
1) Add additional tags
This is a way for teachers to tell us at school, by adding an empty label at the end of the floating element such as <p style= "Clear:both" ></p&gt, and other label BR etc.





The code is as follows:

<p class = "warp" id = "float1">
<h2> 1) Add extra tags </ h2>
<p class = "main left">. main {float: left;} </ p>
<p class = "side left">. side {float: right;} </ p>
<p style = "clear: both;"> </ p>
</ p>
<p class = "footer">. footer </ p>
Advantages: easy to understand and easy to grasp
Disadvantages: You can imagine how many meaningless empty tags will be added through this method, which will violate the separation of structure and performance. It will be a nightmare in later maintenance. This is unbearably unbearable, so you still recommend after reading this article Stop using it.
2) Use the br tag and its own html attribute
This method is somewhat niche, and br has clear = “all | left | right | none” properties


<p class = "warp" id = "float2">
<h2> 2) Use the br tag and its own html attribute </ h2>
<p class = "main left">. main {float: left;} </ p>
<p class = "side left">. side {float: right;} </ p>
<br clear="all" />
</ p>
<p class = "footer">. footer </ p>

Elegant Demo
Advantages: Slightly stronger semantics than empty tags, and less code
Disadvantage: It also violates the separation of structure and performance, and is not recommended.
3) Set the parent element to overflow: hidden
By setting the overflow value of the parent element to hidden; in IE6, you also need to trigger hasLayout, such as zoom: 1;

code show as below:

<p class = "warp" id = "float3" style = "overflow: hidden; * zoom: 1;">
<h2> 3) Parent element set overflow </ h2>
<p class = "main left">. main {float: left;} </ p>
<p class = "side left">. side {float: right;} </ p>
</ p>
<p class = "footer">. footer </ p>

Advantages: no structural and semantic issues, minimal code
Disadvantages: When the content is increased, it is easy to cause the content to be hidden without automatic line breaks, and the elements that need to be overflowed cannot be displayed. In 2004, POPO found that overflow: hidden would cause the middle key to be invalid, which is not acceptable to me as a multi-tab browser. of. So don't use it anymore
4) The parent element sets the overflow: auto attribute
Also IE6 needs to trigger hasLayout, the demo is almost the same as 3
Advantages: no structural and semantic issues, minimal code
Disadvantages: After multiple nesting, firefox will cause all content to be selected in some cases; the mouseover in IE will cause the outermost module to have scroll bars when the width is changed, etc. Early versions of firefox will generate focus for no reason, etc. ,Do not use
5) The parent element is also set to float
Advantages: no structural and semantic issues, minimal code
Disadvantages: The layout of the elements adjacent to the parent element will be affected, and it is impossible to float all the way to the body. It is not recommended
6) The parent element sets display: table
Elegant Demo
Pros: The structure is semantically correct with very little code
Disadvantages: The properties of the box model have changed, and a series of problems caused by it are not worth the money. It is not recommended.
7) Use: after pseudo-element
It should be noted that after is a pseudo-Element, not a pseudo-class (some CSS manuals call it a "pseudo-object"). Many articles such as clearing floating books are called pseudo-classes, but csser Be strict, this is an attitude.
Because IE6-7 does not support: after, use zoom: 1 to trigger hasLayout.
The method is derived from: How To Clear Floats Without Structural Markup
The full source code is as follows:

code show as below:

<style type = "text / css">
.clearfix: after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {display: inline-block;} / * for IE / Mac * /
</ style>
<!-[if IE]> <style type = "text / css">
.clearfix {zoom: 1; / * triggers hasLayout * /
display: block; / * resets display for IE / Win * /}
</ style>
<! [endif]->

In view of the extremely low market share of IE / Mac, we ignore it directly, and the simplified code is as follows:

code show as below:

.clearfix: after {content: "."; display: block; height: 0; visibility: hidden; clear: both;}
.clearfix {* zoom: 1;}

Pros: The structure and semantics are completely correct, the amount of code is centered
Disadvantages: Improper reuse can increase code size
summary
By comparison, it is not difficult to find that, in fact, there are two types of methods listed above:
First, by adding an empty element at the end of the floating element and setting the clear: both attribute, the after pseudo-element is actually a block-level element whose content is a dot after the content;
Second, by setting the parent element's overflow or display: table properties to close the float, let's explore the principle behind this.
There is a very important concept in CSS2.1, but the domestic technology blogs introduce less, that is, Block formatting contexts (BFC).
This specification has been changed in CSS3, called: flow root, and the trigger conditions are further explained.
So how to trigger BFC?
float values other than none
overflow values other than visible (hidden, auto, scroll)
display (table-cell, table-caption, inline-block)
position (absolute, fixed)
fieldset element
It should be noted that display: table itself does not create BFC, but it will generate anonymous boxes, and display: table-cell in anonymous boxes can create new BFCs, in other words, trigger block-level format The context is an anonymous box, not a display: table. So the effects of BFC created by display: table and display: table-cell are different.
The fieldset element currently doesn't have any information about this trigger behavior in www.w3.org, and it didn't appear until the HTML5 standard. Some browser bugs (Webkit, Mozilla) mention this triggering behavior, but without any official statement. In fact, even though fieldset can create new block-level formatting contexts on most browsers, developers should not take this for granted. CSS 2.1 does not define which properties apply to form controls, nor does it define how to use CSS to style them. User agents may apply CSS properties to these properties, and developers are advised to treat this support as experimental, and later versions of CSS may further standardize this.
BFC features:
1) Block-level formatting context prevents margins from overlapping
When two adjacent block boxes are in the same block-level formatting context, the vertical margins between them overlap. In other words, if these two adjacent block boxes do not belong to the same block-level formatting context, their margins will not overlap.
2) Block-level formatting context does not overlap floating elements
According to regulations, the border of a block-level formatting context cannot overlap the margins of the elements inside it. This means that the browser will create an implicit margin for the block-level formatting context to prevent it from overlapping the floating margin of the floating element. For this reason, adding negative margins to a floating block-level formatting context will not work (Webkit and IE6 have a problem at this point-see this test case).
3) Block-level formatting context can usually contain floats
See: W3C CSS2.1-10.6.7 'Auto' heights for block formatting context roots
In layman's terms: the element that created the BFC is an independent box, and the child elements inside will not affect the outer elements on the layout, and vice versa, and BFC still belongs to the ordinary flow in the document.
At this point, you may understand why overflow: hidden or auto can be closed, because the parent element created a new BFC. For Zhang Xinxu's "Understanding of Overflow and Zoom" Clearing the Float "article, I think the parcel is used to explain the principle of closed float. It is not rigorous enough and has no basis. And said that "Firefox and other browsers do not have the concept of haslayout", then modern browsers have BFC, in terms of performance, hasLayout can be equivalent to BFC.
The display engine of IE6-7 uses an internal concept called layout. Due to the many defects of this display engine itself, many display bugs of IE6-7 are directly caused. When we say an element "gets a layout" or an element "owns a layout", we mean its Microsoft-proprietary hasLayout http://www.php.cn/ ... rties / haslayout. asp is set to true for this. IE6-7 uses the concept of layout to control the size and positioning of elements. Those elements that have a layout are responsible for the sizing and positioning of itself and its children. If an element's hasLayout is false, then its size and position are controlled by the ancestor element that recently owned the layout.
Conditions that trigger hasLayout:
position: absolute
float: left | right
display: inline-block
width: any value except "auto"
height: any value except "auto" (for example, many people use height: 1% to clear the float)
zoom: any value except "normal" (MSDN) http://www.php.cn/ ... properties / zoom.asp
writing-mode: tb-rl (MSDN) http://www.php.cn/ ... ies / writingmode.asp
In IE7, overflow has also become a layout trigger:
overflow: hidden | scroll | auto (This property did not trigger layout in previous versions of IE.)
overflow-x | -y: hidden | scroll | auto (The properties in the CSS3 box model have not been widely supported by browsers. They also did not trigger the layout function in previous versions of IE)
For a more detailed explanation of hasLayout, please refer to the famous article "On having layout" translated by old9 (original English: http://www.php.cn/). Since the old9 blog was walled, the Chinese version address:
IE8 uses a brand new display engine. It is said that it does not use the hasLayout property, so it solves a lot of nasty bugs.
In summary:
Close the float by creating a new BFC in a browser that supports BFC (IE8 +, firefox, chrome, safari);
In browsers that do not support BFC (IE6-7), the float is closed by triggering hasLayout.
Fourth, the closed floating method-excellence
The seven closed floating methods have been listed above. According to the principle of the third section analysis, we find that there are actually more: display: table-cell, display: inline-block, etc. As long as the BFC attribute value is triggered, the closed floating can be closed. Comparing from various aspects, the closed pseudo-element floating float is undoubtedly a relatively good solution. Let's talk about this method in detail below.

code show as below:

.clearfix: after {content: "."; display: block; height: 0; visibility: hidden; clear: both;} .clearfix {* zoom: 1;}
1) display: block causes the generated elements to be displayed as block-level elements, occupying the remaining space;
2) height: 0 to prevent the generated content from destroying the original layout height.
3) visibility: hidden makes the generated content invisible, and allows the content that may be covered by the generated content to be clicked and interacted;
4) Use content: "." To generate content as the last element. As for the content, it is possible to use dots or others. For example, there is classic content: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" in oocss. Some versions may have empty content in the content. Cold is not recommended, firefox will still produce extra space until 7.0 content: "";
5) zoom: 1 triggers IE hasLayout.
Through analysis, it is found that except for clear: both are used to clear the float, other code is nothing more than to hide the content generated by content. This is why other versions of the closed float have font-size: 0 and line-height: 0.
Excellence plan one:
Compared to the method of closing the floating tag with empty tags, the code seems to be somewhat redundant. Through query, it is found that there is a "zero-width space" in the Unicode character, which is U + 200B. This character itself is not visible, so we can omit visibility completely. : hidden the code is as follows:


.clearfix: after {content: "\ 200B"; display: block; height: 0; clear: both;}
.clearfix {* zoom: 1;}.


Excellence plan two:
Proposed by Nicolas Gallagher, Original: A new micro clearfix hack, this method does not have the problem of voids in firefox.


code show as below:

/ * For modern browsers * /
.cf: before, .cf: after {
content: "";
display: table;
}
.cf: after {clear: both;} / * For IE 6/7 (trigger hasLayout) * /
.cf {zoom: 1;}

have to be aware of is:
The above method uses the: before pseudo element. Many people are a little confused about this. When should I use before? Why is Option 1 not available? In fact, it is used to deal with overlapping margins. Because the internal element float creates a BFC, the margin-top of the internal element and the margin-bottom of the previous box overlap. If this is not what you want, then you can add before. If it is just a closed float, after is enough! It is not as stated in the article "Clear Float" in the desert: However, when using only clearfix: after, there will be a vertical margin overlay bug in cross-browser compatibility issues. This is not a bug, it is a BFC characteristic.
In actual development, because of the existence of Unicode characters that are not suitable for GB2312-encoded pages with embedded CSS, solution 7 can completely solve our needs, and improvement solution 2 is waiting for everyone's further practice. Schemes 3 and 4 close the float through overflow. In fact, a new block-level formatting context has been created. This will cause a series of changes in its layout and behavior relative to the float. Clearing the float is just a series of changes. Just a role. Therefore, it is unwise to change the global characteristics in order to close the float, and the risks brought by it are a series of bugs, such as focus in earlier versions of firefox, truncating the absolute positioning layer, and so on. Always understand that if you just need to close the float, don't use overflow instead of "careful use" as mentioned in some articles.
It took me three days to finish writing this css. Why should I clear the float? Clear Articles on Floating Principles. If this article is helpful to you, your message is my greatest support. At the same time, because of limited energy, please point out the errors and deficiencies in the article and encourage them!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.