Why clear float? What is the method of clearing float? Which is the ultimate method?

Source: Internet
Author: User

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 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 do we have to clear the float? 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 orclearing 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.
Twowhy to clear floating
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 this is a common flow After the element floats, the inclusion box has a height of 0(height collapse) due to the absence of other ordinary flow elements.。 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 formattingcontexts
Let's take a look at the various ways to clean up floats:
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 <div style= "Clear:both" ></div&gt, and other label BR etc.

Copy Code

The code is as follows:


<div class= "Warp" id= "FLOAT1" >
<div class= "main left" >.main{float:left;} </div>
<div class= "side left" >.side{float:right;} </div>
<div style= "Clear:both;" ></div>
</div>
<div class= "Footer" >.footer</div>
/[code]
Advantages: Easy to understand
Disadvantage: Can imagine through this method, will add how many meaningless empty tags, the structure and performance of the separation, in the post-maintenance will be a nightmare, it is resolutely unbearable, so you read this article or recommend not to use it.
2) Use the BR tag and its own HTML attributes
This method is somewhat small, BR has clear= "all | Left| Right | None "Property
[Code]
<div class= "Warp" id= "FLOAT2" >
&LT;H2&GT;2) Use the BR tag and its own HTML attributes <div class= "main left" >.main{float:left;} </div>
<div class= "side left" >.side{float:right;} </div>
&LT;BR clear= "All"/>
</div>
<div class= "Footer" >.footer</div>


An elegant Demo
Pros: Slightly more semantic than empty labels, less code
Cons: Also contrary to the structure and performance of the separation, not recommended to use
3) parent element Settings Overflow:hidden
The overflow value is set to hidden by setting the parent element, and haslayout, such as Zoom:1, is also triggered in IE6;

Copy Code

The code is as follows:


<div class= "Warp" id= "FLOAT3" style= "overflow:hidden;*zoom:1;" >
<H2>3) parent element Settings Overflow <div class= "main left" >.main{float:left;} </div>
<div class= "side left" >.side{float:right;} </div>
</div>
<div class= "Footer" >.footer</div>

Advantages: There is no structural and semantic problems, the code is very small  
Disadvantage: When content increases, it is easy to cause the content to be hidden and the elements that need to overflow cannot be displayed; 04 Popo found overflow: Hidden will cause the middle key to fail, which is unacceptable to me as a multi-tabbed browsing control. So do not use  
4) The parent element sets the Overflow:auto property  
also IE6 need to trigger Haslayout, demo and 3 almost  
Advantages: There is no structural and semantic problems, the code is very small  
Cons: After multiple nesting, Firefox will cause the content to be selected in some cases, and the mouseover in IE will have a scroll bar in the outermost module when the width is changed. Firefox early version will not cause focus and so on, please see Whining's Demo, do not use  
5) The parent element also sets the floating  
Pros: No structural and semantic issues, minimal code  
Disadvantage: The layout of elements adjacent to the parent element is affected, it is not possible to float to the body all the time,   is not recommended;
6) The parent element is set display:table 
Elegant Demo  
Advantages: The structure semantics is completely correct, the code quantity is very few  
Disadvantage: Box model properties have changed, resulting in a series of problems, not worth the candle, not recommended to use &NBSP;
7) use: After pseudo element  
It is important to note that after is a pseudo-element (pseudo-element), not a pseudo-class (some CSS manuals are called "pseudo-objects"), many of the articles such as the removal of floats are called pseudo-classes, but csser to be rigorous, this is an attitude. &NBSP
Because Ie6-7 does not support: After, use zoom:1 to trigger haslayout.  
The method derives from: How to Clear floats without structuralmarkup 
The original code is as follows:  

Copy Code

The code is as follows:


<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]-->


Given the very low market share of IE/MAC, we directly ignore it, and the final streamlined code is as follows:

Copy Code

The code is as follows:


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


Pros: The structure and semantics are completely correct and the code is centered
Cons: Improper reuse will result in increased code volume
Summary
By contrast, we are not difficult to find, in fact, the above enumerated methods, there are two types:
First , by adding an empty element at the end of the floating element, set theClear:bothProperties, Afterpseudo-elements are actually also passedcontentat the back of the element, a block-level element with content of one point is generated; 
Secondly, by setting the parent elementOverfloworDisplay:Tableproperty to close the float,Let's talk about the principle here.
In CSS2.1 there is a very important concept, but the domestic technology blog introduced less, that is block formatting contexts (block-level formatting context), hereinafter referred to as BFC.
CSS3 This specification has been changed, called: Flow root, and the trigger conditions are further explained.
So how do you trigger BFC?
Float value other than none
Overflow values other than visible (Hidden,auto,scroll)
Display (Table-cell,table-caption,inline-block)
Position (absolute,fixed)
FieldSet elements
Note that display:table itself does not create BFC, but it generates an anonymous box (anonymous boxes), and Display:table-cell in the anonymous box can create a new BFC, in other words, The block-level formatting context is triggered by an anonymous box, not display:table. So the BFC effect created by display:table and Display:table-cell is not the same.
The fieldset element does not currently have any information about the triggering behavior in www.w3.org until the HTML5 standard appears. Some browsers bugs (Webkit,mozilla) mention the triggering behavior, but there is no official statement. In fact, even if fieldset can create a new block-level formatting context on most browsers, developers should not take it for granted. CSS 2.1 does not define which properties apply to form controls, nor does it define how to use CSS to add styles to them. User agents may apply CSS properties to these properties, suggesting that developers use this support as an experimental feature, and that later versions of CSS may further regulate this.
Features of the BFC:
1) block level formatting context blocks margin overlays
When two adjacent block boxes are in the same block-level formatting context, the vertical margin between them will overlap. In other words, if the two adjacent block boxes do not belong to the same block-level formatting context, their margins are not superimposed.
2) block-level formatting contexts do not overlap floating elements
As a rule, the bounding rectangle 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 margin of the floating element. For this reason, it will not work when you add a negative margin to a block-level formatting context that is next to floating (WebKit and IE6 have a problem at this point-you can see this test case).
3) block-level formatting contexts can often contain floating
See: css2.1-10.6.7 ' Auto ' Heights forblock formatting context roots
In layman's terms: the element that created the BFC is a separate box in which the child elements do not affect the outside elements on the layout, and vice versa, while BFC still belong to the normal flow in the document.
At this point, you may understand why Overflow:hidden or auto can be closed because the parent element creates a new BFC. For Zhang Xin Xu in the "Overflow and zoom" clear floating "of some understanding" in the article to use the package to explain the principle of closed floating, I think is not rigorous, and there is no basis. and said "Firefox and other browsers do not have the concept of haslayout", then the modern browser is BFC, from the performance, Haslayout can be equated with BFC.
Ie6-7 's display engine uses an internal concept called layout, which, due to the many flaws in the display engine itself, leads directly to many of the ie6-7 's display bugs. When we say an element "get layout", or an element "has layout", we mean it's Microsoft proprietary properties Haslayouthttp://msdn.microsoft.com/worksh ... rties/ Haslayout.asp is set to true for this purpose. Ie6-7 uses the concept of layout to control the size and positioning of elements, and those elements that have layouts (with layout) are responsible for the sizing and positioning of their own and their child elements. If the haslayout of an element is false, its size and position are controlled by the ancestor element that recently owns the layout.
Conditions for triggering haslayout:
Position:absolute
Float:left|right
Display:inline-block
Width: Any value except "Auto"
Height: Any value except "Auto" (for example, many people will use height:1% to clear the float)
Zoom: Any value except "normal" (MSDN) Http://msdn.microsoft.com/worksh ... properties/zoom.asp
WRITING-MODE:TB-RL (MSDN) Http://msdn.microsoft.com/worksh ... ies/writingmode.asp
In IE7, overflow also becomes a layout trigger:
Overflow:hidden|scroll|auto (this property does not have the ability to trigger layout in previous versions of IE.) )
Overflow-x|-y:hidden|scroll|auto (attributes in the CSS3 box model have not yet been widely supported by the browser.) They also did not trigger layout in the previous IE version)
Haslayout For more detailed explanations see the famous "on have Layout" article of OLD9 translations (in English: http://www.satzansatz.de/cssd/ onhavinglayout.htm), due to OLD9 blog by wall, Chinese version address:
IE8 used a new display engine, allegedly not using the Haslayout attribute, and thus solved a lot of hated bugs.
Sum up:
The BFC-enabled browser (Ie8+,firefox,chrome,safari) closes the float by creating a new BFC;
In browsers that do not support BFC (IE6-7), the float is closed by triggering the haslayout.
Four, closed floating method--Excellence
The above has listed 7 methods of closed floating, through the third section of the principle of analysis, we found that in fact, more: Display:table-cell,display:inline-block, etc. as long as the trigger BFC property values can be closed floating. From all sides,After pseudo element closed floating is undoubtedly a relatively good solution, the following detailed talk about the method.

Copy Code

The code is as follows:


. clearfix:after {content: "."; Display:block; height:0; Visibility:hidden; Clear:both; }
. clearfix {*zoom:1;}


1) Display:block causes the generated elements to appear as block-level elements, occupying the remaining space;
2) height:0 Avoid creating content that destroys the height of the original layout.
3) Visibility:hidden makes the generated content invisible and allows content that may be generated to be covered by the content can be clicked and interacted with;
4) Through the content: "." Generate content as the last element, whether it is a point or anything else is OK, such as oocss inside there is a classic content: "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", some versions may be content Inside the content is empty, a trace of cold is not recommended to do so, Firefox until 7.0content: "" will still produce extra space;
5) zoom:1 trigger IE haslayout.
The analysis found that, in addition to Clear:both used to clear the float, the other code is nothing more than to hide the content generated, which is why other versions of the closed float font-size:0,line-height:0.
Excellence Programme One:
Relative to the empty label closed floating method code seems to be somewhat redundant, through the query found that the Unicode character character has a "0 width space", that is, u+200b, the character itself is not visible, so we can completely omit the Visibility:hidden

Copy Code

The code is as follows:


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


Excellence Programme II:
By Nicolas Gallagher Big Wet Proposed, original: A new micro Clearfix hack, this method also does not exist in Firefox gap problem.

Copy Code

The code is as follows:


/* For modern browsers */
. cf:before,.cf:after {
Content: "";
display:table;
}
. cf:after {Clear:both;} /* for IE 6/7 (trigger haslayout) */
. CF {zoom:1;}


It is important to note that:
The above method used: Before pseudo-elements, a lot of people are confused about this, in the end when I need to use before it? Why is the plan not? In fact, it is used to handle margin overlap, because the inner element float creates the BFC, which causes the margin-top of the inner element and the margin-bottom of the previous box to occur superimposed. If this is not what you want, then you can add before, if only a simple closed floating, after is enough! Not as the desert "Clear Float" article: But only when using clearfix:after when the cross-browser compatibility problem There will be a vertical margin overlay bug, this is not a bug, BFC should have the features.
In the actual development, the improvement scheme one because of the existence of Unicode characters do not fit in the embedded CSS GB2312 encoded page, the use of scenario 7 can completely solve our needs, improve the program two await the further practice of everyone. Scenario 3, 4 closed floating through overflow, has actually created a new block-level formatting context, which will result in a series of changes in its layout and relative to the floating behavior, and clearing the float is only a function of a series of changes. Therefore, in order to close the float to change the global characteristics, it is unwise, the risk is a series of bugs, such as the early version of Firefox to focus, truncated the absolute location of the layer and so on. Always understand that if you just need to close the float, overflow do not use, rather than some of the article said "careful use."

Why clear float? What is the method of clearing float? Which is the ultimate method?

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.