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

Oliver Wolf
1 min readJan 10, 2022

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).

I usually solve this problem in another way which works quite well for me. Instead of writing:

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

I write:

// The css of the isolated component
.resuable-isolated-component {
...other css
}
// The css in the specific project I use the component
.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 generic (semantic) HTML (the CSS Zen Garden approach). If the requirements allow it, I choose the second one.

Best Regards,

Oliver, working on MonsterWriter

--

--