Vertical margins on different elements that touch each other (thus have no content, padding, or borders separating them) will collapse, forming a single margin that is equal to the greater of the adjoining margins. This does not happen on horizontal margins (left and right), only vertical (top and bottom).
To illustrate, take the following HTML:
And the following CSS:
margin: 0 0 20px 0;
margin: 10px 0 0 0;
In this example, the h2 element is given a bottom margin of 20px. The paragraph element, which immediately follows it in the source, has a top margin set at 10px.
Common sense would seem to suggest that the vertical margin thickness between the h2 and the paragraph would be a total of 30px (20px + 10px). But due to margin collapse, the actual thickness ends up being 20px.
Margins of inline-block boxes do not collapse (not even with their in-flow children).
If you change the display of the block elements (such as h2 and p) to a value of inline-block, then the margins will collapse as you are expecting.
The following table summarizes some of the different versions of HTML that have been implemented over the years.
To insert a comment anywhere within your HTML document, enter
<!-- comment -->
where comment is the text of the HTML comment.
A comment can be spread across several lines as long as the comment begins with <!-- and ends with -->.
© 2021 Digcode.com