This is an expected behavior of float positioning.
When an element is floated to the left (in your case the .inline
div), the following content flows down the right side of that element, line boxes get shortened BUT the width of the containing block which is established by the following element (in your case the .yellow
div) is reserved.
This is documented in the spec:
Since a float is not in the flow, non-positioned block boxes created
before and after the float box flow vertically as if the float did not
exist.
However, the current and subsequent line boxes created next to
the float are shortened as necessary to make room for the margin box
of the float.
Which means block level elements (such as <div>
, <p>
, …)—That are not positioned—ignore the float, whereas line boxes flow along its side.
An example given by W3C:
The IMG box is floated to the left. The content that follows is
formatted to the right of the float, starting on the same line as the
float. The line boxes to the right of the float are shortened due to
the float’s presence, but resume their “normal” width (that of the
containing block established by the P element) after the float.
Hence if you give the .yellow
element a background, you’ll see that it spans the container and continues through the floated element.
The solution
From CSS level 2.1 spec:
The border box of a table, a block-level replaced element, or an
element in the normal flow that establishes a new block formatting
context (such as an element with ‘overflow’ other than ‘visible’) must
not overlap the margin box of any floats in the same block formatting
context as the element itself.
Hence if you add an overflow
property with value other than visible
to the .yellow
div, it prevents the div from overlapping the floated element:
.yellow {
overflow: hidden;
}
Overlapping makes sense specially in situations where the length of the following content is large enough to continue normally after the floated element.
If it was restricted by default, the content wouldn’t be continued under the floated element.