The dumb of the reporters: this is an article for the powerful gods. I have made an in-depth analysis of float, and put the float almost naked and naked in front of the masses of good young people.
Float is an attribute that we love and hate. Love, because through floating, we can easily layout; hate, floating left behind too many issues need to be addressed, especially IE6-7 (the following no special instructions refer to Windows platform IE browser ). Maybe many people have such questions: Where does floating come from? Why should we clear the float? What is the principle of clearing float? This article will further analyze the mysteries and make floating more handy.
1. Clear floating or closed floating (enclosing float or clearing float )?
Many people have used to call it "Clear floating". I used to call it this way, but it is not accurate. We should treat them with a rigorous attitude.CodeTo help us better understand the three problems at the beginning.
1) Clear floating: Clear the corresponding word is clear, and the attribute in the corresponding CSS is clear: Left | right | both | none;
2) closed floating: more accurately, it means that floating elements are closed to reduce the impact of floating.Reporter Note: You have potatoes, you have tomatoes, and you have potatoes. ^_^
For the differences between the two, seeElegant demo
Through the above examples, we found that the effect we want to achieve is more specifically closed floating, rather than simply clearing floating, set clear on footer: both clearing floating does not solve the warp height collapse problem.
Conclusion: Closed floating is more rigorous than clearing floating. Therefore, it is called closed floating.
2. Why clear the float?
To answer this question, we must first talk about the positioning mechanism in CSS: normal stream, floating, and absolute positioning (where "position: fixed" is a subclass of "position: absolute ).
1) normal stream: Many people orArticleIt is called a document stream or a Common Document Stream. In fact, there is no such word in the standard Reagan. Document flow is an English document flow, but there is only one word in the standard, calledNormal stream(Normal flow), or a regular flow. But it seems that people are more accustomed to the name of the Document Stream, because many Chinese translation books come in this way. For example, in CSS mastery, from the beginning to the end of the original English book, there is only the word normal flow (normal flow), and there has never been a document flow (document flow)
2) floating: A floating box can be moved left and right until its outer edge encounters an edge of the contained box or another floating box. A floating box does not belong to a normal stream in the Document. When an element floats, it does not affect the layout of block-level boxes, but only the arrangement of inline boxes (usually text, the normal stream in the document will behave like the floating box does not exist. When the floating box height exceeds the include box, in this case, the contained box does not automatically extend to close the floating element (the "height collapse" phenomenon ). As the name suggests, it is just floating on a normal stream, just like a floating cloud, but only floating around.
It is precisely because of this floating feature that, after the elements in the normal stream are floating, the height of the contained box is 0 (the height collapsed) because there are no other elements in the normal stream ). In the actual layout, this is often not what we want, so we need to close the floating element so that its contained box shows a normal height.
The absolute positioning is not much to say. It is not within the scope of this article and will be broken down next time.
3. How floating is cleared-Understanding haslayout and block formatting contexts
Let's take a look at the methods to clear the floating:
1) add additional labels
This is a method that the school teacher told us by adding an empty label at the end of the floating element, such as <Div style = "clear: both"> </div>, other tags such as BR can also be used.
< Div Class = "Warp" ID = "Float1" > < H2 > 1) add additional labels </ H2 > < 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 >
Elegant demo
Advantages: easy to understand
Disadvantages: we can imagine how many meaningless empty labels will be added in this method, which violates the separation of structure and performance. It will be a nightmare in later maintenance, which is intolerable, so after reading this article, I suggest you stop using it.
2) use the BR tag and its own HTML attributes
This method is widely used. BR has the clear = "All | left | right | none" attribute.
< Div Class = "Warp" ID = "Float2" > < H2 > 2) use the BR tag and its own HTML attributes </ H2 > < Div Class = "Main left" > . Main {float: Left ;} </ Div > < Div Class = "Side left" > . Side {float: Right ;} </ Div > < BR Clear = "All" /> </ Div > < Div Class = "Footer" > . Footer </ Div >
Elegant demo
Advantage: The syntax is slightly stronger than that of null tags, and the amount of code is small.
Disadvantage: it also violates the separation of structure and performance and is not recommended.
3) parent element overflow: hidden
Set the overflow value of the parent element to hidden. in IE6, haslayout needs to be triggered, for example, Zoom: 1;
< Div Class = "Warp" ID = "Float3" Style = "Overflow: hidden; * ZOOM: 1 ;" > < H2 > 3) set overflow for the parent Element </ H2 > < Div Class = "Main left" > . Main {float: Left ;} </ Div > < Div Class = "Side left" > . Side {float: Right ;} </ Div > </ Div > < Div Class = "Footer" > . Footer </ Div >
Elegant demo
Advantage: There is no structure or semantic problem, and the amount of code is very small
Disadvantage: when the content increases, it is easy to cause the content to be hidden without automatic line breaks, and the elements to overflow cannot be displayed. In Popo 04, overflow: hidden will cause the middle key to fail, this is unacceptable as a multi-label browser control. So do not use it anymore.
4) set the overflow: auto attribute for the parent element.
Similarly, IE6 needs to trigger haslayout. The demo is similar to 3.
Advantage: There is no structure or semantic problem, and the amount of code is very small
Disadvantages: after multiple nesting, Firefox may select all content in some cases; When Mouseover in IE changes the width, the outermost layer module may have a scroll bar and so on. In earlier Firefox versions, focus will be generated for no reason, see Zookeeper'sDemo, Do not use
5) The parent element is also set to float
Advantage: There is no structure or semantic problem, and the amount of code is very small
Disadvantage: the layout of elements adjacent to the parent element is affected and cannot be moved to the body all the time.
6) set the display: Table for the parent element.
Elegant demo
Advantage: The structure semantics is completely correct, and the amount of code is very small.
Disadvantage: The Box Model attributes have been changed, resulting in a series of problems that are not worth the candle and are not recommended.
7) Use: After pseudo element
It should be noted that after is a pseudo element, not a pseudo class (in some CSS manuals it is called a "pseudo object "), many articles such as clearing the floating book are called pseudo classes, but it is an attitude that csser should be more rigorous.
Because the IE6-7 does not support: After, use ZOOM: 1 to trigger haslayout.
This method is derived from: how to clear floats without structural Markup
The original 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] -->
In view of the extremely low market share of IE/Mac, we ignore it directly. The final code is as follows:
. Clearfix: After{Content:".";Display:Block;Height:0;Visibility:Hidden;Clear:Both;}. Clearfix{* Zoom:1;}
Elegant demo
Advantage: the structure and semantics are completely correct, and the amount of code is centered
Disadvantage: improper reuse may increase the amount of code
Summary
Through comparison, we can easily find that the methods listed above are nothing more than two types:
First, add an empty element at the end of the floating element and set the clear: Both attribute, the After pseudo element is actually a block-level element with the content generated after the element as a vertex;
Second, the floating is closed by setting the parent element overflow or the display: Table attribute. Let's discuss the principles described here.
There is a very important concept in css2.1, but there are few technical blogs in China, that is, block formatting contexts (Block-level formatcontext), hereinafter referred to as BFC.
In css3, this specification was changed, called flow root, and the trigger conditions were further described.
So how to trigger BFC?
- Float values except none
- Value (hidden, auto, scroll) other than visible in Overflow)
- Display (Table-cell, table-caption, inline-block)
- Position (absolute, fixed)
- Fieldset Element
Note that the display: Table itself does not create BFC, but it will generate an anonymous box (anonymous boxes), while the display: Table-cell in the anonymous box can create a new BFC, in other words, the anonymous box instead of display: Table is used to trigger block-level formatting. Therefore, the effect of BFC created through display: Table and display: Table-cell is different.
The fieldset element does not have any information about this trigger behavior in www.w3.org until it is available in the HTML5 standard. Some browsers, bugs (WebKit, Mozilla), mentioned this trigger, but there is no official statement. In fact, even if fieldset can create block-level formatting contexts in most browsers, developers should not take this for granted.CSS 2.1 does not define which attributes apply to Form Controls, nor does it define how to use CSS to add styles to them. The user agent may apply CSS attributes to these attributes. It is recommended that developers regard this support as an experimental feature. Higher CSS versions may further regulate this feature.
Features of BFC:
1) block-level formatting context prevents overlay of the outer margin
When two adjacent block boxes are in the same block-level formatting context, the vertical margin between them is superimposed. In other words, if the 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 outer margin of its elements. This means that the browser will create an implicit margin for the block-level formatting context to prevent it from overlays with the floating element margin. For this reason, when a negative margin is added to a block-level formatting context, it does not work (WebKit and IE6 have a problem at this point-you can refer to this test case ).
3) block-level formatting context can usually contain floating
For details, see W3C css2.1-10.6.7 'auto' heights for block formatting context roots.
In general, the element that creates BFC is an independent box. The child elements in the box do not affect the elements outside the layout, and vice versa, at the same time, BFC is still a common stream in the document.
So far, you may understand why overflow: hidden or auto can be closed and float, because the parent element creates a new BFC. I think it is not rigorous and there is no basis for Zhang xinxu's article understanding of overflow and zoom "Clear floating" to explain the principle of closed floating with a package.And said,"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 IE6-7's Display engine uses an internal concept called layout, which directly leads to a lot of display in the IE6-7 due to its many defects.
Bug. When we say that an element "gets layout", or an element "Owns layout", we mean that its Microsoft proprietary attribute haslayout is set to true. The IE6-7 uses the concept of layout to control the size and positioning of elements, and those with the layout (have layout) are responsible for the size setting and positioning of themselves and their child elements. If the haslayout value of an element is false, its size and position are controlled by the ancestor element with the most recent 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, height: 1% is used when many people 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 attribute does not trigger layout in earlier versions of IE. )
- Overflow-x |-Y: hidden | scroll | auto(Attributes in the css3 box model have not been widely supported by browsers. They did not trigger layout in earlier ie versions)
For more detailed explanations of haslayout, see the well-knownOn having LayoutAn article (English: http://www.satzansatz.de/cssd/onhavinglayout.htm), because the old9 blog by the wall, Chinese Version address:
IE8 uses a brand new Display engine. It is said that the haslayout attribute is not used, so it solves many bad bugs.
To sum up:
In browsers that support BFC (IE8 +, Firefox, chrome, and Safari), create a new BFC closed floating;
In browsers (IE6-7) that do not support BFC, close the float by triggering haslayout.
Iv. Closed Floating Method-keep improving
Seven closed floating methods have been listed above. By analyzing the principles in section 3, we can find more: Display: Table-
Cell, display: inline-block, etc. can be closed and floating as long as the BFC attribute value is triggered. Compared from various aspects, the closed floating of the After pseudo elements is undoubtedly a relative ratio.
The solution is better. The method is described in detail below.
. Clearfix: After{Content:".";Display:Block;Height:0;Visibility:Hidden;Clear:Both;}. Clearfix{* Zoom:1;}
1) display: blocks display the generated elements at the block level, occupying the remaining space;
2) Height: 0 to prevent the height of the original layout from being damaged by the generated content.
3) visibility: hidden makes the generated content invisible and allows you to click and interact with the content that may be covered by the generated content;
4) use content :". "The generated content is the last element. It can be vertices or other elements in content. For example, oocss contains the classic content:" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ", in some versions, the content may be blank, and it is not recommended to do this if it is cold. Firefox will still generate additional gaps until 7.0 content;
5) ZOOM: 1 triggers ie haslayout.
After analysis, we found that except for clear: Both, other code is used to hide the content generated by the content, which is why other versions of closed floating have Font-size: 0, line-Height: 0.
Optimization solution 1:
The code of the method with the empty tag closed and floating seems to be somewhat redundant. It is found through the query that there is a "zero-width space" in the Unicode character, that is, U + 200b, this character is invisible, so we can omit visibility: hidden.
. Clearfix: After{Content:"\ 200b";Display:Block;Height:0;Clear:Both;}. Clearfix{* Zoom:1;}.
Optimization solution 2:
Proposed by Nicolas Gallagher, original article: A New Micro Clearfix hack, this method does not have any gaps in Firefox.
/*For modern browsers*/. Cf: before,. Cf: After{Content:"";Display:Table;}. Cf: After{Clear:Both;}/*For IE 6/7 (trigger haslayout)*/. Cf{Zoom:1;}
Note that:
The above method uses the before pseudo element. Many people are confused about this. When should I use before? Why does solution 1 fail? In fact, it is used to deal with the overlap of the margin. Because the internal element float creates BFC, the margin-top of the internal element overwrites the margin-bottom of the previous box. If this is not what you want, you can add before. If it is just closed and floating, after is enough! Not as mentioned in the desert clear float article: but when we only use Clearfix: After, there will be a vertical margin overlay bug in cross-browser compatibility. This is not a bug, is what BFC should have.
SeeElegant demo
For more information, see Clearfix improvement and overflow: hidden explanation.
In actual development, solution 1 is improved because Unicode characters are not suitable for pages embedded with CSS gb2312 encoding. Solution 7 can completely solve our needs, solution 2 is awaiting further implementation. Solution 3 and 4 closed the floating through overflow. In fact, a new block-level formatting context has been created, which will lead to a series of changes in its layout and behavior relative to the floating, clearing floating is only a function of a series of changes. Therefore, it is unwise to change the global characteristics by closing the float. The risk is a series of bugs, such as the focus generated in earlier versions of Firefox and the layer with absolute positioning truncated. Always understand that if you only need to close the float, overflow should not be used, rather than the "use with caution" mentioned in some articles ".
It took three days to write this article. If this article is helpful to you, your message is my greatest support. At the same time, due to limited energy, you are welcome to point out the errors and deficiencies in this article!
References:
- Page breaks and block-formatting contexts: allowed page breaks (13.3.3)
- Clearfix and block formatting contexts: everything you know about Clearfix is wrong
- Block formating contexts, "haslayout"-ie window vs css2.1 browsers: simulations.
- New block formatting contexts next to floats
- Control Block formatting Context
- On having layout, [translation] on having layout http://old9.blogsome.com/2006/04/11/onhavinglayout
- "Haslayout" Overview
- Haslayout Property
- IE haslayout
- Https://developer.mozilla.org/en/CSS/block_formatting_context
Http://www.iyunlu.com/view/css-xhtml/55.html