CSS Margin Collapse

CSS Margin Collapse: Now and then two margins collapse into a single margin.

The CSS margin property is used to set a margin on all four sides of an element.

At the point when two elements are next to each other on a page vertically, one of the elements may lose its vertical margin. This means the top and bottom margins of elements are now and again combined into a single margin. The single margin is equivalent to the largest of the two margins getting collapsed.


Margin Collapse

Top and bottom margins of elements are now and then collapsed into a single margin that is equivalent to the largest of the two margins.

This doesn’t occur on left and right margins! Just top and bottom margins!

Look at the following example:

Example
Demonstration of margin collapse:

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
  margin: 0 0 50px 0;
}

h2 {
  margin: 20px 0 0 0;
}
</style>
</head>
<body>

<p>In this example the h1 element has a bottom margin of 50px and the h2 element has a top margin of 20px. So, the vertical margin between h1 and h2 should have been 70px (50px + 20px). However, due to margin collapse, the actual margin ends up being 50px.</p>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

</body>
</html>

In the example above, the <h1> element has a bottom margin of 50px and the
<h2> element has a top margin set to 20px.

Common sense would seem to suggest that the vertical margin between the <h1> and the <h2>would be a total of 70px (50px + 20px). In any case, because of margin collapse, the actual margin ends up being 50px.


All CSS Margin Properties

PropertyDescription
marginA shorthand property for setting the margin properties in one declaration
margin-bottomSets the bottom margin of an element
margin-leftSets the left margin of an element
margin-rightSets the right margin of an element
margin-topSets the top margin of an element

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your projects with us.


0 Comments

Leave a Reply

Avatar placeholder