Home >Web Front-end >CSS Tutorial >Why Does `float: left` Not Change the Width of a Div?

Why Does `float: left` Not Change the Width of a Div?

DDD
DDDOriginal
2024-10-27 20:57:301091browse

Why Does `float: left` Not Change the Width of a Div?

Why CSS Float Fails to Modify Div Width

Issue Description

In CSS, the float: left property is expected to shift subsequent elements leftwards instead of creating a new line. However, in a scenario like the given example, the second div continues to span the entire width, defying expectations. The content, on the other hand, aligns correctly.

Explanation of Behavior

This behavior is inherent in float positioning. When an element is floated (the .inline div in this case), content flows around its right side. Line boxes are shortened to accommodate the float's margin box, but the width of the containing block (established by the .yellow div) remains reserved. This is specified in the CSS spec.

Solution

To prevent the .yellow div from overlapping the floated element, one can add an overflow property with a value other than visible. This forces the browser to create a new block formatting context, preventing the overlap.

The above is the detailed content of Why Does `float: left` Not Change the Width of a Div?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn