css margin collision

2019-03-06 08:46发布

问题:

Is there a way to detect margin-collision and prevent it? like if I have

<div style="margin-bottom: 10px;"></div>
<div style="margin-top: 10px;"></div>

I get 20px space between them, but I need 10px instead?

回答1:

You do not need to do anything; by the box model specs, adjacent bottom and top margins will collapse, so you get a 10-pixel gap between your two <div> elements as opposed to a 20-pixel gap. See this jsFiddle preview.

EDIT: the reason why you're not seeing a collapse between a <table> ad a <div> is because a table is set to display: table by default, which is not exactly the same as a block-level element, so by the specs the margins will not collapse.



标签: css margin