Say you’ve got a
<Card /> component. It’s highly likely it shouldn’t be butted right up against any other components with no spacing around it. That’s true for… pretty much every component. So, how do you handle component spacing in a design system?
Do you apply spacing using margin directly on the
<Card />? Perhaps
margin-block-end: 1rem; margin-inline-end: 1rem; so it pushes away from the two sides where more content natural flows? That’s a little presumptuous. Perhaps the cards are children inside a
<Grid /> component and the grid applies a
gap: 1rem. That’s awkward, as now the
<Card /> component spacing is going to conflict with the
<Grid /> component spacing, which is very likely not what you want, not to mention the amount of space is hard coded.
Different perspectives on component spacing
Eric Bailey got into this recently and looked at some options:
- You could bake spacing into every component and try to be as clever as you can about it. (But that’s pretty limiting.)
- You could pass in component spacing, like
<Card space="xxl" />. (That can be a good approach, likely needs more than one prop, maybe even one for each direction, which is quite verbose.)
- You could use no component spacing and create something like a
<Layout />component specifically for spacing between components. (It breaks up the job of components nicely, but can also be verbose and add unnecessary DOM weight.)
This conversation has a wide spectrum of viewpoints, some as extreme as Max Stoiber saying just never use
margin ever at all. That’s a little dogmatic for me, but I like that it’s trying to rethink things. I do like the idea of taking the job of spacing and layout away from components themselves — like, for example, those content components should completely not care where they are used and let layout happen a level up from them.
Adam Argyle predicted a few years back that the use of
margin in CSS would decline as the use of
gap rises. He’s probably going to end up right about this, especially now that flexbox has
gap and that developers have an appetite these dats to use CSS Flexbox and Grid on nearly everything at both a macro and micro level.