Not quite like this particular question on Stack Overflow, mine doesn't involve float issues but rather troubles with applying margins to a block-level element's only child.
I encountered a dilemma while attempting to add a margin to an only-child of a block-level element:
#parent {
background: rgba(255, 0, 0, 0.1);
}
#child {
margin: 30px 0;
padding: 20px;
background: rgba(0, 255, 0, 0.1);
}
<div id="parent">
<div id="child">Foo</div>
</div>
Despite the margin being applied, the parent's background fails to show up unless siblings are added before and after the #child
, or by setting any non-visible value for overflow
. The same example below shows how overflow affects it:
#parent {
background: rgba(255, 0, 0, 0.1);
overflow: auto;
}
#child {
margin: 30px 0;
padding: 20px;
background: rgba(0, 255, 0, 0.1);
}
<div id="parent">
<div id="child">Foo</div>
</div>
Referring to CSS2.1 Section 9.4.1 - Block Formatting Contexts, I discovered the following explanation:
Floats, absolutely positioned elements, block containers (like inline-blocks, table-cells, and table-captions) that aren't block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
The reasoning behind the "overflow other than visible" logic in this scenario seems perplexing to me. It appears that the margins are unaffected as the sole change is the background. Can someone clarify why using overflow: visible
leads to such behavior?