Why does browser sometimes collapse margins of an element?
The problem is with the definition of "margin". According to the box model, the margin is not part of the box. The margin is outside the box. According to the box model, the box only contains the content, the padding, and the border. When we declare the height and width for the element, we declare the height and width for its content. To determine the actual height and width of the box, we need to add the padding and border.
The margin is not part of the box. It is defined as the minimum space surrounding the element. If we have 2 paragraph next to each other, we may expects the spacing between the two paragraphs to be 2x (where x is the margin declared for each paragraph), but the spacing between the two paragraphs is actually 1x.
When do browser collapse margins?
Margin-collapsing only happens with top and bottom margins for block level elements. Margin-collapsing does not happen for left and right margin, and not at all on inline elements.
Margin collapsing happens wherever two (or more) top or bottom margins are touching. When they touch, instead of getting the sum of the two margins, the bigger one is used, and the smaller one is ignored.
What happened when negative margins are involved?
Negative margins are special and the browsers deal with negative margin in the following way:
- Work out what margins are touching
- Ignore all negative margins
- Perform the collapse as if there were no negative margins (select the largest positive margin)
- Select the largest of the negative margins, and subtract it from the margin from step 3
What margin is used when two elements are nested?
This is the part the cause most problems for web developers. Supposed that we have:
<div style="margin-top:10px"> <div style="margin-top:20px"> A </div> </div>
What margin is used? The resulting margin will be max(10,20) which is 20px.
Do browsers collapse margins on floated / positioned elements?
How to prevent margin-collapsing?
If you suspect that you have problem caused by margin-collapsing, make sure that margin-collapsing do not happen. To do this, make sure that margins do not touch each other. One way to do that is by adding a border, or padding (of at least 1px) to one element or the other element.