Vertical Margins of Two different HTML block elements merge into a single Margin
Yeah, We know this is often confusing part for most of the HTML, CSS developers. In this article, let us make it clear for you..
Vertical Margins i.e margin-top and margin-bottom of HTML Block level elements like div, paragraph, heading etc..collapse into a single margin. To better understand, let us consider an example.
Here, We have two paragraphs with first paragraph having margin-bottom of 50px and the second paragraph has margin-top of 20px. You may assume total 70px margin will be created between these two elements. However, the new margin between two paragraph elements is 50px. This is called Margin Collapse. In this case, maximum of two margins i.e maximum of 50px and 20px is picked up.
Use Case 2 : With Negative Margins
Let us modify the above example a bit by modifying margins to negative numbers as shown below.
<!DOCTYPE html> <html> <head></head> <body> <p style="margin-bottom:-50px"> First Paragraph </p> <p style="margin-top:-20px"> Second Paragraph </p> </body> </html>
The new resulting margin will be the smallest negative number which is -50px. We can inspect the margin details by running the above HTML in browser and inspecting paragraph elements. The respective screenshot is shown below.
If Only one of the margins is negative, then the resulting margin will be sum of both the margins. For eg:, if margin-bottom is 50px and margin-top of next element is -20px, the resulting margin is 50px + -20px i.e 30px.
Use Case 3: Equal Positive Margins
When Two block elements have same positive vertical margins, only one margin will be applied. For Eg: If margin-bottom of first block element is 50px and the second block element is 50px, then the resulting margin is 50px.
The better way to handle or avoid margin collapse is to stick to a single vertical margin. What we mean is use either only margin-top for the elements or only margin-bottom.