The methods for clearing floats include clearboth, setting clearfix, overflow and setting double pseudo-elements to the parent element
When we write code, sometimes Because of the use of float elements, some elements on the page cannot be displayed correctly. In the following article, we will introduce several methods of clearing floats in detail. It has certain reference value and I hope it will be helpful to everyone.
【Recommended course: CSS course】
##Floating Consequences:
(1) Since the floating element is out of the document flow, the height of the parent element cannot be expanded, affecting elements at the same level as the parent element (2) and Non-floated elements at the same level of the floating element will follow it, because the floating element leaves the document flow and does not occupy its original position
(3) If the floating element is not the first floating element, the elements before it also need to be floated , otherwise it will easily affect the structural display of the page
<style> .box{border:1px solid #ccc;background:pink;} .red{width:100px;height:100px;background: red;} .green{width:100px;height:100px;background:green;} .blue{width:100px;height:100px;background: blue;} </style> <body> <div class="box"> <div class="red"></div> <div class="green"></div> <div class="blue"></div> </div>
How to clear the float
(1) Use clear:both to clear floats
<div style="clear: both"></div>
(2) Use pseudo-element clearfix to clear Float
Adds an :after pseudo-element to the parent element. By clearing the float of the pseudo-element, it achieves the purpose of supporting the height of the parent element.clearfix:after{ content:""; display:block; visibility:hidden; clear:both; }
(3) Use of overflow method
When the overflow style is set to the parent element, whether it is overflow:hidden or overflow:auto, the float can be cleared as long as its value is not visible. Its essence is Constructed a BFC, which achieves the effect of supporting the height of the parent element.box{border:1px solid #ccc;background:#eff2f4;overflow: auto}
(4) Use of double pseudo-element method
.clearfix:before,.clearfix:after { content: ""; display: block; clear: both; }
The above is the detailed content of What are the methods to clear floats?. For more information, please follow other related articles on the PHP Chinese website!