CSS Floating and Flaot and Clear floating

float

First, understand that div takes up an entire line, even if the size of the next div can fill the remaining space

Float floats an element out of the flow, to the left or right, and to the right if there is space on the previous element’s line.

There are several possible values for float

value describe
left Left floating
right Right float
none Not floating, default value
inherit Inherits the value of the parent element

If we want to place div3 to the right of div2, what should we do?

The first idea might be to add float:left to div3;

????? It seems that contrary to what I thought, DIV3 will not be as I thought, he is still in place.

However, div4 seems to have changed. Div4 has gone up and he’s right behind Div2

Emm, come to think of it, div4 rising is normal, because div3 is floating, the empty space is filled by Div4

But but but why doesn’t div3 go up to the row where div2 is? I mean, there’s room for that

This is an important feature of float:

  1. If the previous element of a floating element is also floating, that element will follow the previous element
  2. If the last element was in the standard flow, the element’s relative vertical position does not change.

With that in mind, we can give div2 a float:left;

clear

Let’s talk about clear float

In the previous example, we managed to have div2 and div3 on the same line

However, div4 rises to the same position as div2. What if we want div4 to be below div2?

We’ll give div4 a float:left; Let it float, but what if the line div2 is in is long?

Emmm, again, doesn’t work. It doesn’t work the way we want it to

Clear means clear — clear the float

There are several possible values

value describe
none Default, allowing floating objects on both sides
left Floating objects on the left are not allowed
right Floating objects on the right are not allowed
both Do not allow

Div4 has a floating object on the left. Add a clear:left to div4.

Dude, div4 came out ahead, and he did exactly what we wanted

conclusion

  1. Float lets elements float left or right out of the document flow
  2. Clear clears floating elements to the left or right of an element, placing that element to the far left or right. Note that clear does not affect other elements, but only the element that uses it
  3. Study more hands, when you see here I want you to do it yourself