-
There are many ways to clear floats, such as using the clear attribute that comes with the br tag, using the element's overflow, using empty tags to set clear:both, etc. But considering compatibility issues and semantic issues, we generally use the following code to clean up floats.
/* Clear floats*/ .clearfix:after { visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0; } .clearfix { zoom:1; }
The principle is to use the :after pseudo-class in an "advanced" browser to add an invisible block content other than display:none after the floating block. And set clear:both to it to clear floats. Add haslayout to the floating block in IE6 and 7 to make the floating block raised and affect the document flow normally.
The above code should be the current mainstream way to clean up floats. Alipay now uses this method.
Now, Nicolas Gallagher has given a more concise solution:
.cf:before, .cf:after { content:""; display:table; } .cf:after { clear:both; } .cf { zoom:1; }
The principle is still the same. Use the :after pseudo-class to provide clear:both after a float. The difference is that display: table is used to hide this blank space. Instead of setting visibility:hidden;height:0;font-size:0; such a hack.
It is worth noting the :before pseudo-class here. In fact, it is used to process top-margin while folding, and has nothing to do with cleaning up floats. But because floating creates a block formatting context, if another element on a floating element happens to have a margin-bottom and this floating element happens to have a margin-top, they should not be collapsed (although this is uncommon) .