I have successfully gotten the margin of the h2 element to be contained within its container - the section element. This way it doesn\'t collapse with the margin of the p elemen
Since elements with overflow set to anything other than visible can't have their margins collapsed, why does the effect I've successfully achieved only work when the container (section) element is set to auto? Why does it not work when the h2 element is set to auto?
This is not true. overflow will disable the margin collapsing between the element and its inflow first (or last) child and not with its siblling. Overflow create a Block Formatting Context and this will isolate all the elements inside from any outside interaction.
h2 {
margin:10px 0;
overflow:auto; /* this will do nothing */
}
.box {
margin:10px 0;
outline:1px solid red;
}
<div class="box">
<h2>some text</h2>
<h2>some text</h2>
</div>
<div class="box" style="overflow:auto;">
<h2>some text</h2>
<h2>some text</h2>
</div>
In the above example, all the margin will collapse but not the ones between the second section and its childs h2.
When we take away the margin of the p element, and don't have section set to auto, h2 loses its upper-margin. Why does this happen? It doesn't seem to be in contact with another margin which would make it collapse.
The h2 will collpase with the margin of section which is 0 and the resulting margin will be moved to section:
p {
margin: 0;
}
section {
/*overflow: auto;*/
background:red;
}
<header>
<p>I am a p element
</p>
</header>
<section id="profile-section">
<h2>I am an h2 element</h2>
</section>
Even if an element has a margin equal to 0 it can collapse with other margin: