CSS Note: How to make Child's margin contribute to parent's height!
CSS really bothers me, whenever I have to use it, I find out more unwritten untold shitty rules! Here we are gonna discuss one of those rules:
Default behavior is that a child element's margin does not affect the height of its parent. Take a look at the snippets below, and how they get rendered in a browser:
.html:
<body> <div id="parent1"> <p id=child1>This is Child 1</p> </div> </body>
.css:
#parent1 { background: lightcoral; } #child1 { margin: 30px 0;
}
and here is the result:
Now if I add a border to the parent element not only the border is added but also The child element's margin will be part of the content area of it's parent child. Child's margin will contribute to parent's height. I'm just gonna add another div tag just the same as what we already have, and apply the following CSS rule to it:
border: dotted;
see the difference:
Does this make any sense? Why is it behaving like that?
Well I found an explanation (which didn't really convince) I'm gonna quote it here may be it persuades you that this is the best possible behavior:
So long as the parent has no border, there is the possibility that the child's bottom margin might be collapsed with another element below it. Once the border is defined, that's not possible.