Margin Collapsing

suggest change

When two margins are touching each other vertically, they are collapsed. When two margins touch horizontally, they do not collapse.

Example of adjacent vertical margins:

Consider the following styles and markup:

div{
    margin: 10px;
}
<div>
    some content
</div>
<div>
    some more content
</div>

They will be 10px apart, since adjoining vertical margins collapse. The spacing is not the sum of the two margins.

Example of adjacent horizontal margins:

Consider the following styles and markup:

span{
    margin: 10px;
}
<span>some</span><span>content</span>

They will be 20px apart, since horizontal margins do not collapse. The spacing is the sum of the two margins. There is no whitespace between the spans in the markup, so no extra text space is added.

Overlapping with different sizes

.top{
    margin: 10px;
}
.bottom{
    margin: 15px;
}
<div class="top">
    some content
</div>
<div class="bottom">
    some more content
</div>

These elements will be spaced 15px apart vertically. The margins overlap as much as they can, but the larger margin will determine the spacing between the elements.

Overlapping margin gotcha

.outer-top{
    margin: 10px;
}
.inner-top{
    margin: 15px;
}
.outer-bottom{
    margin: 20px;
}
.inner-bottom{
    margin: 25px;
}
<div class="outer-top">
    <div class="inner-top">
        some content
    </div>
</div>
<div class="outer-bottom">
    <div class="inner-bottom">
        some more content
    </div>
</div>

The spacing between the two texts is 25px. All four vertical margins adjoin, so they collapse to the largest of the four.

Now, what about if we add some borders to the markup above.

div{
    border: 1px solid red;
}

The spacing between the two texts is 64px. Borders stop parent and child margins from collapsing, but the adjoining margins of .outer-top and .outer-bottom still collapse to max(10px, 20px), which is 20px. From the first text to the second that is the inner bottom border (1px), the inner bottom margin (15px), the outer bottom border (1px), the collapsed margin between the outers (20px), the next outer’s top border (1px), the next inner top margin (25px), and that inner top border (1px).

Collapsing Margins Between Parent and Child Elements:

HTML:

<h1>Title</h1>
<div>
  <p>Paragraph</p>
</div>

CSS

h1 {
  margin: 0;
  background: #cff;
}
div {
  margin: 50px 0 0 0;
  background: #cfc;
}
p {
  margin: 25px 0 0 0;
  background: #cf9;
}

Only the largest margin applies. The div has margin-top: 50px and the p has margin-top: 25px. Adding them would suggest 75px between the heading and the paragraph, but the adjoining margins collapse to 50px.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents