I know how to fix it, but my question is why this happens. I have a Parent section and inside a Child div. The thing is that when placing margin: 20px in the child, a margin is applied to everything, not only the child, which is where I wanted to apply it with respect to the parent. Why does it apply to everything? I know that it is solved by placing a position: absolute to the parent. But without this, because it applies to all my content, parent and child. Do you have any explanation?
body{
margin: 0 auto;
padding: 0;
}
#padre{
width: 400px;
height: 400px;
background: orange;
}
#hijo {
width: 100px;
height: 100px;
background: green;
margin:20px;
}
<body>
<section id="padre">
<div id="hijo" >1</div>
</section>
</body>
The explanation is that this is called "collapsed margins".
This occurs in three main cases:
As we can see, in the example you expose, the second case "Father and first/last child" applies. I applied a 1px transparent border to demonstrate what the documentation says: "If there is no border or... separating the parent margin-top from the child margin-top,..." , then adding the border basically doesn't they collapse.
References:
https://www.w3.org/TR/CSS2/box.html#collapsing-margins
https://www.w3.org/TR/CSS2/visuren.html#block-formatting
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing