



























Mar 24, 2020·Updated Aug 11, 2024
77,558 views
We should ban margin from our components.
Hear me out.
A component should not affect anything outside it's own visual boundaries. Defining margin inside a component adds “invisible” space outside the component's visual boundaries.
One specific margin around a component cannot be ideal for all instances of the component. Different layouts and contexts require different spacing.
Defining margin in a component defines it globally for all instances of the component. But designers think about space in relation and context: they define how far a component should be from another component in a specific layout/context, not globally.
Instead of margin I have started using spacers (either -components or -class names), which move the responsibility of managing space to the parent-level.
For example, the Braid design system popularized the idea of a Stack component:
<Stack space={3}>
<Item />
<Item />
<Item />
</Stack>
TailwindCSS popularized space between and gap (for flexbox and grid) utility class names:
<div className="space-x-3">
<Item />
<Item />
<Item />
</div><div className="gap-3 flex">
<Item />
<Item />
<Item />
</div>
Under the hood, both spacer components and class names still use the margin CSS properties with a lobotomized owl selector or the gap property (for flexbox and grid layouts):
.space-x-3 > * + * {
margin-top: 0.75rem;
}.gap-3 {
gap: 0.75rem;
}
Moving the responsibility of managing space to the parent-level has benefits that aren't obvious.
Using spacers means none of your components define their own margins. Instead, you exclusively define how far a component should be from another component in a specific instance with a spacer.
Spacers force you to define space in relation and context instead of globally for all instances of a component at once. Who else thinks about space in relation and context? Designers.
Spacers can restrict spacing values to steps on a scale. (e.g., space-x-3 -> margin-left: 0.75rem) That way, all spacing automatically aligns to a grid and is consistent.
So: Use spacers. Ban margin.
I am not the first one to realize this. Thanks to @markdalgleish, @michaeltaranto and @mattcompiles at Seek, as well as my good friend @okonetchnikov for paving the way and prompting me to think about it.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。