Collapsing margins


#1

Question

What is the reason behind collapsing on horizontal margins and not vertical?

Answer

The main reason why we can get collapsing margins on top/bottom values is that one of the rules for collapsing to happen is for an element to be a block type element. for example, if we have two divs together:

<div id="one" class="div-one">
</div>
<div id="two" class="div-two"> 
</div>

they will both be by default block elements, which means they will be one, on top of the other, to make them visible (since they don’t have any content) this will be their css:

.div-one {
  height: 50px;
  background-color: papayawhip;
}

.div-two{
  height: 50px;
  background-color: cyan;
}

and we will see:

Thus, if they both have top and bottom margins, we would have collapsing margins since they both are block elements.

So with the adjustment:

.div-one {
  height: 50px;
  background-color: papayawhip;
  margin-bottom: 20px;
}

.div-two{
  height: 50px;
  background-color: cyan;
  margin-top: 10px;
}

we will see:

the bottom div’s (.div-two) margin is still there, but it has become part of the overall margin of 20px. This capacity of block elements (once we are aware) allows for an easier and cleaner separation between elements to be even.

It is not a quality of inline elements, and that is the main reason why there is no collapsing on vertical values, since having elements side to side can only be made by changing the way the element is displayed, from being a block element to an inline element:

.div-one {
  display: inline;
  background-color: papayawhip;
  padding: 50px; /*padding gives the inline div volume. Width and height do not apply. */
  margin-right: 20px; 
}

.div-two{
  display: inline;
  background-color: cyan;
  padding: 50px;
  margin-left: 10px;
}

20%20PM

leading to having to account for how we should manipulate our margins.