Margin considered harmful

Mar 24, 2020·Updated Aug 11, 2024

77,558 views

We should ban margin from our components.

Hear me out.

The problems with using margin in a component

1. Margin breaks component encapsulation

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.

2. Margin makes components less reusable

One specific margin around a component cannot be ideal for all instances of the component. Different layouts and contexts require different spacing.

3. Margin conflicts with how designers think

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.

Use spacers instead

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;
}

The benefits of spacers

Moving the responsibility of managing space to the parent-level has benefits that aren’t obvious.

1. Spacers force us to build more encapsulated, and thus reusable, components

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.

2. Spacers bring us closer to how designers think

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.

3. Bonus: Spacers keep our spacing consistent

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.

Average: 1,04 essays/year