Basic doubt with margin. Father and son css

7

I know how to solve it, but my doubt is in why this happens. I have a Father section and inside a Son div. The thing is that by placing margin: 20px on the child, a margin is applied to everything, not just the child that is where I wanted to apply it to the father. Why is it applied to everything? I know that it is solved by placing a position: absolute to the father. But without this, because it applies to all my content, father and son. Do you have an 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>
    
asked by Ralexhx 12.04.2018 в 06:50
source

1 answer

4

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

    
answered by 12.04.2018 / 07:13
source