When two elements are stacked on top of each other and both have some margin, you would expect that the space between the elements would be equal to the total margin; This does not happen though, the resultant margin is something ambiguous.
This margin collapse is really annoying!
Why does this happen? how do I avoid this margin collapse?
Margins collapse by default... Use padding instead
My usual strategies:
Either
Put padding on the wrapper instead of margin on the child
Or
Only ever apply vertical margins to one side (ie only on the bottom of an object so you can't get top + bottom interference of two objects)
Sunny Singh
Creating Content & Code
I don't know the reason why this happens, I assume it is a legacy browser bug, but there is a great MDN article and CSS-Tricks article that has good information on this.
As others have mentioned, your primary solutions are:
margin-topormargin-bottomwhen spacing elements.It also seems like there are various scenarios in which margins don't collapse, such as with floated or absolutely positioned elements, but I think it's safer to use the listed suggestions every time.