How to handle spacing between components

CSS grid gap, when to use margin and padding, and CSS units of measurement.

The use of space is a big part of any design. Translating spacing to CSS in your HTML can get tricky. These are the rules I follow for setting up spacing for my layouts.

Layout spacing

For your overall layout, using CSS grid will go a long way to simplify your spacing needs as you’ll be able set a gap between elements. This takes care of a lot of requirements among components by separating layout spacing from the components themselves, allowing them to be self-contained without any margins set.

Where to place space

How do you decide where to place margins for elements that aren’t using CSS grid gap for spacing? My rule of thumb is to always add margins at the end, on the right if needed, and at the bottom. And then take out the extra margin if it’s not needed, like for the last element in a component. You can use :last-child to do this:

.component {
  margin-right: 20px;
  margin-bottom: 20px;

  &:last-child {
    margin-right: 0;
    margin-bottom: 0;
  }
}

For components that need space within them, padding should be used. For example, a component with a title, and paragraph text should have padding defined at the top and bottom, and left and right. However, the title and text elements themselves should have margins set for their own spacing.

.component {
  padding: 10px 20px;

  & h1, p {
    margin-bottom: 1.25rem;
  }
  & p {
    &:last-child {
      margin-bottom: 0;
    }
  }
}

Units of measurement

As far as what unit of measurement to use for spacing, it depends. Pixels can be used for your CSS grid gap, along with padding and margins for components. But for text elements, text should use relative rem units for the text size, which means that their margin should also be rems to match.

For additional examples, you can view source the CSS on this site. Or refer to this boilerplate template that I use for setting up my layouts.


Thanks for reading! If you enjoyed this post, buy me a coffee to have something to sip on as I write my next one.

Consider sharing this post with others: copy this link | send an email

And follow my updates to get my latest posts.