This answer aims to add some alternatives for those who need to change the default CSS behavior that culminates in margin collapse .
Alternative 1: hidden element (hack!)
One of the palliative solutions to avoid the effect of margin collapse is to include a hidden element between the two border elements.
Example:
<div class="wrapper">
<div class="box"></div>
<div class="hidden">.</div>
<div class="box"></div>
<div class="hidden">.</div>
<div class="box"></div>
</div>
.hidden {
overflow: hidden;
height: 0px;
width: 0px;
}
For criticism of creating additional elements, note that even using ::after
or ::before
via CSS also there is an overhead , after all the browser needs to internally create that element. The same goes for other tags that generate additional processing.
Additionally, the user has not set a number of elements. You can not assume that one solution is bad because it is not for thousands of items, when that amount is an exception and not the rule in general web development. In fact, any large number of items can crash certain systems and we would have to throw away several web frameworks that encapsulate complex components.
Alternative 2: doubling the margin
For those who did not like the first hack, a more specific workaround would be to increase the bottom margin of the elements. To "correct" the remaining margin at the end you can use last-child
.
The CSS of this case:
.box {
background-color: black;
box-sizing: border-box;
height: 48px;
width: 100%;
margin: 14px 0px 7px 0;
}
.box:first-child {
margin: 7px 0;
}
Well, some still did not like this solution, although there was nothing absurd about it. But for those who want to find the egg, I changed it from last-child
to first-child
because apparently in old browsers (IE) may perform better .
Alternative 3: inline-block
The last alternative is to use the @bfavaretto response .
The reason I did not post an alternative using inline-block
from the beginning is that the browser adds additional spaces between the blocks and I did not really investigate the reason.
But after resusciting the topic a few months later, I decided to do the research and the solution was, after all, very simple.
Additional spacing is caused due to font properties, so a font-size
is sufficient to solve the problem.
Let's see:
.box {
background-color: black;
box-sizing: border-box;
height: 48px;
width: 100%;
margin: 7px 0;
display: inline-block;
}
.wrapper {
font-size: 0;
}