Do You Really Know About the Float?

The float attribute is commonly used in CSS. But, if it is used improperly, unexpected effects will occur. That's why I choose this topic for the page.

Introduction About float

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.

The characteristics of float

Wrap

float characteristic - wrap
Fig 1. Float characteristics - wrap
*Hover on the image to enlarge.

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.

Adaptive

float characteristic - adaptive
Fig 2. Float characteristics - adaptive
*Hover on the image to enlarge.

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.

Height Collapse

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.

Blocklize

float characteristic - blocklize
Fig 3. Float characteristics - blocklize
*Hover on the image to enlarge.

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.

No overlap of margins

float characteristic - no overlap margin
Fig 4. Float characteristics - no overlap margin
*Hover on the image to enlarge.
no float - overlap margin
Fig 5. No float - overlap margin
*Hover on the image to enlarge.

The element with the float attribute does not have any margin overlap, which is different from the margin overlap of normal element.