Home >Web Front-end >CSS Tutorial >Common uses of floats in CSS and introduction to clearing floats (code example)
This article brings you the common usage of floats in CSS and the introduction of clearing floats (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Floating is a relatively troublesome attribute in CSS, and it is usually accompanied by clearing the float. Today we are going to fix the float together.
In fact, when we set an element to float, the effect achieved is as follows:
I believe everyone has seen this layout. Many magazines will use this kind of illustration on the left or right and the effect of text wrapping.
Another common usage of floating is as follows:
That is, within a certain line, make a certain part right-aligned, Usually it is not implemented with margins, but with floats.
The floating element cannot support the parent element, which will cause the height to collapse! !
Look at the following example:
<div> <div></div> <div></div> </div> .container { background-color: lightblue; font-size: 0; } .son1 { display: inline-block; width: 50px; height: 50px; background-color: orange; } .son2 { width: 100px; height: 100px; float: right; background-color: lightgray; }
When the larger block floats, we can see it Unable to expand parent element. Normally this is not what we want as it leads to a confusing layout. This is especially obvious when all child elements within a parent element are floated, and the height of the parent element will collapse to 0.
Therefore, when we use floats and don’t want this to happen, we need to clear the floats .
There may be many ways to clear floats, but it is more popular now. My personal favorite is as follows:
First, add the following CSS:
.clearfix:after { content: '.'; display: block; height: 0; visibility: hidden; clear: both; }
Then, in Add the clearfix class on the parent container, and the final code is as follows:
<div> <div></div> <div></div> </div> .container { background-color: lightblue; font-size: 0; } .son1 { display: inline-block; width: 50px; height: 50px; background-color: orange; } .son2 { width: 100px; height: 100px; float: right; background-color: lightgray; } .clearfix:after { content: '.'; display: block; height: 0; visibility: hidden; clear: both; }The effect obtained is as follows:
Floating elements can expand the height of the parent container! Summary
The above is the detailed content of Common uses of floats in CSS and introduction to clearing floats (code example). For more information, please follow other related articles on the PHP Chinese website!