They Say: Do Not Use Margins in CSS. How I use them anyway.

Recently I read more and more posts (e.g. here (HN), here) which state that the use margins in your CSS should be avoided and that there are modern alternatives to spacing.

This is because, when you apply a margin on an element, it does not affects the element itself but its surrounding. Hence it is considered to destroy the encapsulate/isolation of the element. This is a problem when you want to reuse your element in another project or even in the same project. I think this argument is easy to follow and viable.

The proposed solutions to this problems is the CSS flex-layout feature called “gap” or spacer components (see, here, here).

So far I solved this problem in another way which works for me quite well, instead of writing:

.component {
margin: 5px;
...other css
}

I write:

.resuable-isolated-component {
...other css
}
.container .resuable-isolated-component {
margin: 5px;
}

The benefit of this is a clean and semantic HTML structure. In general you have to decide if you want to have a generic CSS (the Tailwind CSS approach) or a semantic HTML (the CSS Zen Garden approach). If the requirements allow it, I choose the later one.

Best Regards,

Oliver, working on MonsterWriter