Home >Web Front-end >CSS Tutorial >Why Does `overflow: auto` Make a Container Expand to Fit Floated Elements?
Why Does 'overflow: auto' Expand Container Height to Accommodate Floated Elements?
When implementing a two-column layout with floated elements, you may encounter an issue where the container does not expand vertically to fit its floating children. Adding 'overflow: auto' to the container solves this problem.
Understanding Floats
Float elements are positioned outside the regular document flow, appearing to float next to other elements. As such, the parent container is unaware of the existence of floated elements and will not account for their height when calculating its own height.
Clearance and Overflow
To force the parent container to accommodate its floated children, you need to either clear the floats or establish a new block formatting context (BFC). Overflow: auto is a CSS property that creates a new BFC.
How Overflow: Auto Creates a BFC
Overflow: auto establishes a BFC by satisfying certain conditions, including:
Benefits of Establishing a BFC
By establishing a BFC, the following occurs:
Note on Clear Floats
Overflow: auto does not clear floats; it only creates a BFC. To clear floats, you must add a clearing element, such as a div with 'clear: both' style, after the floated elements. However, a parent element cannot clear its own floating children.
The above is the detailed content of Why Does `overflow: auto` Make a Container Expand to Fit Floated Elements?. For more information, please follow other related articles on the PHP Chinese website!