Why do vertical margins disappear when the parent is set to overflow:visible? If it's set to overflow:hidden margins are visible again. It seems counterintuitive.
I think I understand how overflow is supposed to work when content of an element can't fit into it, but I don't understand what is happening with the margins.
Here's an example: ( http://jsfiddle.net/VrVc7/ )
#outer {
background-color:#EEE;
overflow:hidden;
}
#inner {
margin: 30px;
padding: 5px;
background-color:#ABE;
}
<div id="outer">
<div id="inner">abc</div>
</div>
How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.
When Vertical Worlds Collide. Collapsing margins happen when two vertical margins come in contact with one another. If one margin is greater than the other, then that margin overrides the other, leaving one margin.
Vertical margins on different elements that touch each other (thus have no content, padding, or borders separating them) will collapse, forming a single margin that is equal to the greater of the adjoining margins. This does not happen on horizontal margins (left and right), only vertical (top and bottom).
The first thing that stops collapsing is situations where there is something between the elements in question. For example, a box completely empty of content will not collapse it's top and bottom margin if it has a border, or padding applied. In the example below I have added 1px of padding to the box.
It's called collapsing margin
. As per W3c
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
How to prevent from collapsing margin
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With