Thứ Năm, 8 tháng 5, 2014

Problem "Container does not stretch to fit floated contents" and how to use ClearFix technique to solve it?


Getting this problem?


Problem: A parent div with child element which has float property affects the parent div or makes it disappear.

Collapsing and Clearfix
One typical issue when using floats, is that parent elements don’t resize to fit their floated children. That makes sense, as they are removed from the normal flow. The solution to this is usually through a technique called Clearfix hack. A clearfix is a technique for an element to automatically clear after itself, thus preventing collapse.

Hack-free approach
Overflow: hidden is very popular method to clear floats without adding extra markup. But it becomes undesirable in few circumstances where placing the absolute positioned element, then it cuts off the element. So we can make use of different methods.


Normally, you can apply something like the following to the outer div:

  1. height: 1%; overflowhidden;  

In most modern browsers, the container will now stretch to fit the floated contents.

Clear Parent Element In CSS Using Clearfix
In some circumstances, especially when support for ancient browsers is required, there’s also a generally trouble-free hack.

The clearfix hack is used to clear floated divisions (divs) without using structural markup. 



  1. /* new clearfix */  
  2. .clearfix:after {  
  3.     visibilityhidden;  
  4.     displayblock;  
  5.     font-size: 0;  
  6.     content" ";  
  7.     clearboth;  
  8.     height: 0;  
  9.     }  
  10. * html .clearfix             { zoom: 1; } /* IE6 */  
  11. *:first-child+html .clearfix { zoom: 1; } /* IE7 */  

Yes it’s ugly, but it works very well, enabling designers to clear floats without hiding overflow and setting a width or floating (nearly) everything to get the job done.

Now simply add:
  1. class="clearfix"  

Note: Some people uses the clearfix technique in slightly different way, for example:
  1. .clearfix:after {  
  2.      content".";   
  3.      displayblock;   
  4.      height: 0;   
  5.      clearboth;   
  6.      visibilityhidden;  
  7. }  

Notice the line containing the content: "."; property. I have found that the period (or dot) specified in quotes has a nasty tendency to break certain layouts. By adding a literal dot after the .clearfix division (i.e., via the .clearfix:after selector), the clearfix hack creates a stumbling block for certain browsers. And not just for Internet Explorer — depending on the layout, even Firefox will choke a layout upon tripping on an :after-based pseudo-dot.

Use a space instead of a dot to prevent breaking layouts
The solution to this subtle design chaos? Replace the literal dot with a single blank space: "content: " "; — this trick has proven successful so consistently that I now use it as the default property in every clearfix hack.

References: