The float attribute can move the element to the right or left until its outer edge touches the border of its container or another floated element. The floated element will get rid of the document flow, and will not take any space in the flow. So other elements will behave as if the floated element doesn't exist. That's why the float attribute can affect the page layout. To put it in another way, it lets the block-level elements ignore the floated elements and lets the inline elements wrap around the floated elements.
When the width of the parent element is bigger than the floated child element, the width of the floated child element equals to the width of the image in this example.
If we add some text after the floated image, the width of floated child element will expand to the width of its parent element, which is 600px in this example.
This is a very important feature of float. As you can see from Fig 1, the height of the div#outside is 0 and does not expand according to the div#inside. When the div#inside is floated, its height is considered to be 0, thus the content inside of div#outside is 0. It seems like there's no child element inside of div#outside.
You can set the height and width of the floated element even if it's an inline element. However, this floated inline element won't behave like a block-level element.
The element with the float attribute does not have any margin overlap, which is different from the margin overlap of normal element.
We can use the feature of float to disrupt the normal document flow to implement some text wrapping layout.
We can use clear to solve the height collapse problem when we use float. You can set clear with none, left, right or both.
It's worth noting that when we use clear (not set to none), the float is still there and has not been cleared! Only the effects of floating can be removed.
Value | Explanation |
---|---|
none | The default value, allowing floating objects on both sides |
left | Floating objects on the left are not allowed |
right | No floating objects on the right are allowed |
both | Floating objects are not allowed on both sides |
If an element contains only floated elements, its height collapses to nothing. If you want
it to
always be able to resize, so that it contains floating elements inside it, you need to
self-clear
its
children. This is called clearfix, and one way to do it is to add clear to a replaced
::after
pseudo-element on it.
(clear - CSS, MDN Web
Docs)