CSS Float Behavior: Understanding Div Width Preservation
When applying the float:left property to an HTML element, it's expected that following elements will be pushed to the left rather than wrapping to a new line. However, in certain circumstances, it may appear that the div width is unaffected.
In the given example, the content of the second div (with class="yellow") is aligned correctly, but the div itself still spans the full width of the container. This behavior stems from the fundamental nature of float positioning.
When an element is floated, it is removed from the normal flow of the document. However, the space occupied by the floated element is still "reserved" by the subsequent element that would have occupied that space.
This reservation of space is documented in the CSS specification, which states that non-positioned block-level elements (such as divs) treat floats as if they did not exist in terms of vertical layout. However, line boxes (the rectangular areas that contain text) are shortened to accommodate the float's margin box.
As a result, the content of the subsequent element flows down the side of the float, but the width of the container (determined by the following unfloated element) remains reserved.
To address this issue, one solution is to apply an overflow property (such as overflow: hidden) to the subsequent element. By doing so, you establish a new block formatting context, which prevents the element from overlapping with the floated element's margin box. This forces the subsequent element to shrink to a size that does not overlap with the float.
The above is the detailed content of Why Does a Floated Element Appear to Not Affect Div Width?. For more information, please follow other related articles on the PHP Chinese website!