Question
What is the reason behind collapsing on horizontal margins and not vertical?
Answer
First, lest address that the collapsing margins are the vertical margins, top and bottom margins, even though they are on the horizontal line of the element (if we go back to the box model) they take into account the window, which is the space where all the elements exist.
Let’s think of it as a grid of boxes. then top and bottom margins will be stacked up one on top of the other, thus being on a vertical line, the same way we can say that the left and right margins will always be one next to the other in a row (generally speaking), thus being placed on a horizontal line.
Now, 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;
}
leading to having to account for how we should manipulate our margins.