Before clearing floats, there are two important definitions to know: the definition of a float: to pull an element out of the flow of the document, to move in a specified direction, to encounter a parent boundary or to stop an adjacent float element. Height collapse: Adaptive height of the parent element of a floating element (if the parent element does not write height, the parent element will collapse after the child element writes a float)
-
Now that we know how to clear floats and why we want to clear them, we need to use the clear float property.
- The clear: left | right | both | none | inherit: element cannot have a direction on the floating element
- Clear :both: no floating elements are allowed on either side.
1, clear clear float (add empty div method)
Add an empty div below the floating element and give it a CSS style: {clear:both; height:0; overflow:hidden; }Copy the code
2. Method: Set the height of the floating element parent
We know that height collapse is caused by the adaptive parent height of the floating element, so we can solve this problem by setting its height appropriately. Disadvantages: Not applicable when floating element height is uncertainCopy the code
3. Method: Float to float (parent float at the same time)
What does "float against float" mean? The parent of the floating element is also floated. Disadvantages: You need to add a float to the parent of each float element, too many floats can cause problems.Copy the code
4. Method: Set parent to inline-block
Disadvantages: parent margin left and right auto invalid, can not use margin: 0 auto; Center of theCopy the code
5, BR clear float
<div class="box">
<div class="top"></div>
<br clear="both" />
</div>
Copy the code
6, add overflow: Hidden float method to parent
Problem: need to match width or zoom compatible IE6 IE7; overflow: hidden; *zoom: 1;Copy the code
7, universal clearance method after pseudo class clearance float (now the mainstream method, recommended use)
Selector :after{content:".";
clear:both;
display:block;
height:0;
overflow:hidden;
visibility:hidden;
}
Copy the code
In order to be compatible with IE6, 7 also needs to work with Zoom. For example:
.clear:after{
content:' ';
display:block;
clear:both;
height:0;
overflow:hidden;
visibility:hidden;
}
.clear{
zoom:1;
}
Copy the code
Things to watch out for:
After pseudo-class: append content inside the element; :after{content"Added content"; } IE6, 7 is not compatible with zoom a, trigger IE hasLayout, so that elements according to their own content calculation width and height. B. FF (Firefox) is not supported.Copy the code