CSS floating issues in a detailed

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 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 the float, set on the footer Clear:both clear floating does not solve the wrap height collapse problem.

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 we close the float?

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 is not present, and when the float box height exceeds the containing box, It will also appear that the inclusion box does not automatically stretch to close the floating element ("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.

Three, the principle of closed floating--understand haslayout and Block formatting contexts

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>, and other label BR etc.

<div class= "wrap" id= "FLOAT1" >

  

an elegant Demo

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

<div class= "wrap" id= "FLOAT2" >

  

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;

<div class= "wrap" id= "FLOAT3" style= "Overflow:hidden; *zoom:1; " ><H2>3) parent element Set overflow 

  

an elegant Demo

Pros: No structural and semantic problems, very little code

Cons: 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 that Overflow:hidden will cause the middle key to fail, which is unacceptable to me as a multi-tabbed browsing control. So don't use it.

4) parent Element Set Overflow:auto property

Same IE6 need to trigger Haslayout, demo and 3 almost

Pros: No structural and semantic problems, very little code

Disadvantage: After multiple nesting, Firefox will cause the content to be selected in some cases, ie in the mouseover cause width changes will appear the outermost module has scroll bar, etc., Firefox earlier version will not cause focus, etc., please see whining Demo , do not use

5) parent element also set floating

Pros: No structural and semantic problems, very little code

Disadvantage: The layout of the elements adjacent to the parent element is affected and cannot be floated to the body, not recommended

6) parent element Settings display:table

an elegant Demo

Pros: The structure is semantically correct and the code is very small

Cons: Box model properties have changed, resulting in a series of problems, not worth the candle, not recommended to use

7) Use: After pseudo element

It is important to note that after is a pseudo-element (pseudo-element), not pseudo-class (some CSS manuals are called "pseudo-objects"), many of the articles such as closed floats are called pseudo-classes, but csser to be rigorous, this is an attitude.

Because IE6-7 does not support: After, use zoom:1 to trigger haslayout.

The method originates 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 haslay Out */  display:block;/* resets display for Ie/win */} </style>  <![ Endif]--> in  view of the IE/MAC market share is very low, we directly ignore, the final streamlined code is as follows:. clearfix:after {content: "."; display:block; height:0; Visibility:hidden; Clear:both; }.clearfix {*zoom:1;}

  

an elegant Demo

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 and setting the Clear:both property, the after pseudo-element is actually a block-level element that generates content as a point after the element in the contents;

Second, by setting the parent element overflow or the Display:table property to close the float, let's explore the principle.

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没有定义哪种属性适用于表单控件,也没有定义如何使用CSS来给它们添加样式。用户代理可能会给这些属性应用CSS属性,建议开发者们把这种支持当做实验性质的,更高版本的CSS可能会进一步规范这个。

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 for block 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 Haslayout Http://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 close 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 uses a new rendering engine that removes Haslayout's original functionality, so it completely eliminates many of the hated bugs, but ie8~ie11 through "document.documentelement.currentstyle.haslayout" Still can get Haslayout logo, I wrote a Test Demo (IE8 in Zoom:1 return false), more detailed see "IE8 Haslayout = True"

In summary: In support of the BFC Browser (Ie8+,firefox,chrome,safari) by creating a new BFC closed floating, in the browser (IE6-7) does not support BFC, by triggering haslayout closed floating.

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 aspects of comparison, after pseudo-element closure floating is undoubtedly a relatively good solution, the following detailed talk about the method.

. 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 bit of cold is not recommended to do so, Firefox until 7.0 content: "" will still produce extra space;

5) zoom:1 trigger IE haslayout.

The analysis found that, in addition to Clear:both used to close 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

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

/* For modern browsers */.cf:before,.cf:after {content: "";d isplay: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.

Please see the elegant demo

For further information, see: Clearfix Improvement and Overflow:hidden detailed translation

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 closed 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."

It took me three days to finish writing this article. If you feel that this article is helpful to you, your message is my greatest support, at the same time because of limited energy, welcome to point out the mistakes and shortcomings in the text, mutual encouragement!

Resources:

    • Page breaks and block-formatting contexts:allowed page breaks (13.3.3)
    • Clearfix and block formatting contexts:everything Know about clearfix are wrong
    • Block formating contexts, "haslayout" –ie window vs CSS2.1 browsers:simulations.
    • New block formatting contexts next to floats
    • Control Block Formatting Context
    • On have 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

CSS floating issues in a detailed

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.