.parent { background-color: red; /* border: blue solid 1px; */} .son {width: 100px; height: 100px; background-color: silver; } .box1 { height: 200px; width: 200px; background-color: pink; }Copy the code

The CSS code looks like this

< div class = "parent" > < div class = "son" > son < / div > < / div > < div class = "box1" > < / div >Copy the code

The display effect can be understood as follows:

Adding float: left to son causes the height of the parent element to be lost, causing son and Box1 to overlap

Clear: left; In this case son and Box1 do not overlap

Here’s something weird: Comment out clear: left and add an upper margin structure to Box1 that doesn’t change the way I expected it to look. Imagine son not moving box1 down 150px;

.parent { background-color: red; /* border: blue solid 1px; */ } .son {width: 100px; height: 100px; background-color: silver; float: left; } .box1 {height: 200px; width: 200px; background-color: pink; /* clear: left; */ margin-top: 150px; }Copy the code

Why did ** son also move down? What’s the reason? Don’t know! If the parent element has no height, giving the parent element a border looks like this:

Height :100px;

That’s normal. Modify the CSS code

.parent{ background-color: red; /* border: blue solid 1px; */ /* height: 100px; */ } .son{ width: 100px; height: 100px; background-color: silver; float: left; } .box1{ height: 200px; width: 200px; background-color: pink; /* clear: left; */ margin-top: 150px; } .clearfix::before{ display: table; content: ''; /* clear: both; */} <div class="parent clearfix"> <div class="son"> </div>Copy the code

To sum up: by default, the height of the parent element is supported by the content of the child element. When float is used, son is removed from the document flow and the height of the parent element is lost. Adding an upper margin to Box1 does not make box1 drop 150px; In fact, son and box1 both move down, as shown in the above tests, if the parent height is stretched, margin-top will work

111

It works, too, without having to write the ClearFix class selector at all. As shown in the figure below.

.parent { background-color: red; /* border: blue solid 1px; */ /* height: 100px; */ } .son{ width: 100px; height: 100px; background-color: silver; float: left; } .box1{ height: 200px; width: 200px; background-color: pink; /* clear: left; */ margin-top: 150px; } < body > < div > 111 < / div > < div class = "parent" > < div class = "son" > son < / div > < / div > < div class = "box1" > box1 < / div > < / body >Copy the code

As for why, I don’t know… Can only say because of blowing to listen!!