This is the 21st day of my participation in Gwen Challenge
First, the concept of floating
It’s like we’re in the middle of an ocean, and it’s not a fixed coral thing in the ocean, it’s floating.
A floating box can move left or right until its outer edge touches the border that contains the box or another floating box. Because the float box is not in the normal flow of the document, the block box in the normal flow of the document behaves as if the float box does not exist. That is, the float is out of the document flow.
Float properties
float: left; // indicates that the element floats to the left of the block container. float: right; // indicates that the element floats to the right of the block container. float: none; // The default value is not floating.Copy the code
As you can see, as the float goes left, the light-colored box at the top is covered by the purple box below because it is out of the document flow. As the float moves to the right, you can see that the light-colored box moves to the right.
Third, the nature of floating
Floating wrap: Actually, I don’t know if you have used the word surround in the picture in Word, it is similar to this. That is, in CSS, text surrounds the image with the float property.
When we use picture + text normally:
<div id="child1">I am a picture<img src="./flower.png" />The picture is a flower</div>
Copy the code
#child2 {
width: 50px;
height: 50px;
background-color: firebrick;
}
Copy the code
When we float the image,
img {
float: left;
}
Copy the code
And you can see the picture sort of comes out. That is, the floating element comes out.
Four, floating common application — height collapse problem
It is easy to cause height collapse when we use floating, as shown in the figure:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
Copy the code
#parent {
border: 1px solid;
}
#child1 {
width: 50px;
height: 50px;
float: left;
background-color: aquamarine;
}
#child2 {
width: 50px;
height: 50px;
float: left;
background-color: firebrick;
}
Copy the code
We also mentioned that height collapse can be resolved by BFC, such as setting overflow property:
#parent {
border: 1px solid;
overflow: hidden;
}
Copy the code
Effect of 👇
Or use the clear float:
#parent {
border: 1px solid;
display:block;
content:'clear';
clear:both;
}
Copy the code
For more details on BFC, see my previous article, “What is BFC?”
conclusion
To sum up, float has always been something I don’t like because it’s out of the flow of documents and it’s easy to “flip” my pages, but even if I don’t like it, I won’t let it “control” me. So still want to know more about floating knowledge, in order to better implement the page.
If there is any mistake, welcome to criticize and correct ~~
Refer to article: MDN documentation