First of all, we need to know that clear:both is the key to clearing floats.
(Recommended tutorial: css quick start)
clear is a positioning attribute in CSS that specifies which side of the element does not allow other floating elements. Then clear:both stipulates that floating elements are not allowed on the left and right sides.
The clear attribute can only work on block-level elements. This is the role of display:block in clearing floating styles.
In addition visibility: hidden;height: 0;As long as the value of content is empty, it doesn’t matter whether it is written or not.
So why do you want to clear the float? The most common reason is because the outer container is highly collapsed. Code demonstration:
<style> .wrap { width: 200px; border: 1px solid #333; } .wrap:after { content: ''; display: block; clear: both; } .left { float: left; background: blue; height: 100px; width: 100px; } .right { float: left; background: red; height: 50px; width: 100px; } </style> <body> <div class='wrap'> <div class="left"></div> <div class="right"></div> </div> </body>
To show it clearly, the content in the .wrap:after style is set to content : 'after pseudo-element', as shown in the figure below.
Then add clear:both to the .wrap:after style, which indicates that floating elements are not allowed on the left and right sides of the after pseudo-element. There is no other way but to put the after pseudo-element. Below, this time is shown in the image below.
Incidentally, the height of the .wrap parent element is propped up, which effectively eliminates floating and solves the problem of height collapse of the outer container.
Then we set the content in the .wrap:after style to content:' ', and finally it is as shown in the figure below.
The above is the detailed content of Introduction to the principle of css clearing floats. For more information, please follow other related articles on the PHP Chinese website!