The explanation is that this is called "collapsed margins".
The vertical margins (upper -top- and lower -bottom-) of the block elements collapse or combine in certain occasions, and the largest margin, or some of them, predominates in case they are equal.
This occurs in three cases mainly:
-
Adjacent brothers:
The margins of the adjacent brothers are collapsed (except when the last brother needs to be cleaned after the floating ones).
-
Parent and first / last child: If there is no border, padding, content online, or cleaned to separate the margin-top of a margin-top block from its first child block, or no edge, padding, content in line, height, min-height, or max-height to separate the margin-bottom from a margin-bottom block of your last child, then those margins collapse. The collapsed margin ends outside the father.
-
Empty blocks: If there is no border, padding, in-line content, height, or min-height to separate the margin-top of a block from its margin-bottom, then its upper and lower margins collapse.
As we can see, in the example that you explain, the second case "Father and first / last child" applies. I applied a transparent border of 1px to demonstrate what the documentation says: "If there is no border or ... that separates the margin-top father from the margin-top child, ..." , then at add the edge, basically do not collapse.
body{
margin: 0 auto;
padding: 0;
}
#padre{
width: 400px;
height: 400px;
background: orange;
border-top: solid 1px transparent;
}
#hijo {
width: 100px;
height: 100px;
background: green;
margin:20px;
}
<section id="padre">
<div id="hijo" >1</div>
</section>
References:
link
link
link