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 vertical margins collapse over one and other. (The spacing will not be the sum of 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 don’t collapse over one and other. (The spacing will be the sum of two margins.)

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>

What will be the spacing between the two texts? (hover to see answer)

!The spacing will be 25px. Since all four margins are touching each other, they will collapse, thus using the largest margin of the four.

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

div{
    border: 1px solid red;
}

What will be the spacing between the two texts? (hover to see answer)

!The spacing will be 59px! Now only the margins of .outer-top and .outer-bottom touch each other, and are the only collapsed margins. The remaining margins are separated by the borders. So we have 1px + 10px + 1px + 15px + 20px + 1px + 25px + 1px. (The 1px’s are the borders…)

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;
}

In the example above, only the largest margin applies. You may have expected that the paragraph would be located 60px from the h1 (since the div element has a margin-top of 40px and the p has a 20px margin-top). This does not happen because the margins collapse together to form one margin.

Feedback about page:

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



Table Of Contents