You will encounter many strange problems when laying out CSS web pages. These problems may be caused by browser bugs or insufficient understanding of CSS properties. This article discusses the issue of CSS margin overlay.
Margin merging means that when two vertical margins meet, they form a single margin. The height of the merged margin is equal to the greater of the heights of the two merged margins. Margin merging (overlapping) is a fairly simple concept. However, when it comes to laying out web pages in practice, it can cause a lot of confusion.
When an element appears above another element, the bottom outer edge of the first element
When an element is contained within another element (assuming there is no padding or border separating the margins), their top and/or bottom margins are also merged. Please look at the picture below:
Although it may seem strange, margins can even merge with themselves.
Suppose you have an empty element that has margins but no border or padding. In this case, the top and bottom margins come together and merge:
If this margin encounters another element's margin, it will also be merged:
This is why a series of paragraph elements takes up very little space, because all their margins are merged together to form a small margin.
Margin merging may seem a little strange at first, but in practice, it makes sense. Take, for example, a typical text page consisting of several paragraphs. The space above the first paragraph is equal to the paragraph's top margin. Without margin merging, the margins between all subsequent paragraphs will be the sum of the adjacent top and bottom margins. This means the space between paragraphs is twice as large as the top of the page. If margin merging occurs, the top and bottom margins between paragraphs are merged together so that the distances everywhere are consistent.
Margin merging only occurs for vertical margins of block boxes in normal document flow. Margins between inline boxes, floated boxes, or absolutely positioned boxes are not merged.