DEV Community

loading...
Cover image for How I learned to stop worrying about the margins and love the gap

How I learned to stop worrying about the margins and love the gap

mattcoady profile image Matt Coady ・1 min read

We've all been in that situation where you're making a navbar or footer that contains multiple action components, like links and whatnot. You're going to need to add a little space between the items so often your first thought is to reach for margins.

    <nav>
      <a href="#" class="button">Home</a>
      <a href="#" class="button">About</a>
      <a href="#" class="button">Portfolio</a>
      <a href="#" class="button">Contact</a>
    </nav>
Enter fullscreen mode Exit fullscreen mode
.button {
  margin-left: 10px;
}
Enter fullscreen mode Exit fullscreen mode

You might even need a little pseudo style to leave the last item unaffected

.button {
  margin-left: 10px;
}

.button:last-child {
  margin-left: 0;
}
Enter fullscreen mode Exit fullscreen mode

Ever since the introduction of gap in css grids and shortly after flexbox, we can hoist this layout concern to the parent... where it should be:

nav {
  display: flex;
  gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Now nav takes full responsibly of the spacing and you can drop anything into the contents of nav, spaced out and ready to go.

This technique is particularly useful in the world of reusable React components where a general use wrapper component can take any child component, render it and space it without the child component being concerned with its own layout.

Discussion (2)

pic
Editor guide
Collapse
inhuofficial profile image
InHuOfficial • Edited

Maybe hang fire on using it in production or find a polyfill for now, gap in flex only has 72% coverage (for example on most iOS devices it doesn't work, although that should fix itself in about 6-12 months as people update).

Great one for future proofing but not quite usable yet unfortunately!

Instead use grid gap perhaps? Grid gap has much better coverage

Collapse
mattcoady profile image
Matt Coady Author

Yes! Absolutely, like all new web features make sure it meets your project standards for usability.

As you mentioned as well this:

nav {
  display: grid;
  grid-auto-flow: column;
  grid-gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

...should produce the same results.