Collapsing margins are probably one of the most annoying features in CSS. Initially, collapsing margins of adjacent objects should help to style collections of objects. However, I never understood how margins of children falling outside the parent should be useful, or why adding background color does not prevent the collapse.
.child {
margin: 30px;
}
/* colors added to visualize boxes */
.blue { background-color: blue; }
.red { background-color: red; }
.gray { background-color: gray; }
<div class="gray">
<div class="child blue">Hello</div>
<div class="child red">Word</div>
</div>
You might expect that the colored boxes have a 30px margin inside the gray box. However, the result looks like this. The top and bottom margins lay outside the gray parent box.
It is worthwhile to have a look at the details when margins collapse.
The next question is how to prevent margin collapse. One of the most obvious solutions are adding padding or adding a border. However, this might conflict with the actual intended design.
In my opinion, the best method, in terms of side effects, to prevent margin collapse is as follows.
.no-collapse::after, .no-collapse::before {
display: table;
content: '';
}
<div class="gray no-collapse">
<div class="child blue">Hello</div>
<div class="child red">Word</div>
</div>
The result looks as expected.
This might also interest you