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.
For criticism of creating additional elements, note that even using
::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
The CSS of this case:
margin: 14px 0px 7px 0;
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
first-child because apparently in old browsers (IE) may perform better .
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.
margin: 7px 0;