How to clear floating in css: 1. Add an empty div tag with the "clear:both" style set after the floating code. 2. Add an after pseudo-element with the "clear: both;" style to the parent element. 3. Set the "overflow: auto" style to the parent element.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
When we write code, sometimes some elements on the page cannot be displayed correctly because of the use of float elements.
But after using float elements, there will be some bad effects:
(1) Since the floating elements are out of the document flow, the height of the parent element cannot be expanded, which affects Elements at the same level as the parent element
(2) Non-floating elements at the same level as the floating element will follow, because the floating element leaves the document flow and does not occupy its original position
(3) If the floating element is not the first If there is a floating element, the elements before it also need to float, otherwise it will easily affect the structural display of the page.
At this time, you need to clear the float. Here are some CSS methods to clear the float.
(1) Use clear:both to clear floating
Put an empty div tag in the code, and then set clear:both to this tag. Clear the effect of floating on the page. Its advantages are simplicity, convenience and good compatibility, but it is generally not recommended to use this method because it will cause structural confusion and is not conducive to later maintenance
<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 the overflow attribute of CSS
When setting the overflow style for the parent element, whether it is overflow:hidden or overflow:auto, you can clear the float as long as its value is not visible. Its essence It is to construct a BFC, so as to achieve the effect of supporting the height of the parent element
.box{ border:1px solid #ccc; background:#eff2f4; overflow: auto }
(Learning video sharing: css video tutorial)
The above is the detailed content of How to clear float in css. For more information, please follow other related articles on the PHP Chinese website!