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>
.button {
margin-left: 10px;
}
You might even need a little pseudo style to leave the last item unaffected
.button {
margin-left: 10px;
}
.button:last-child {
margin-left: 0;
}
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;
}
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.
Top comments (2)
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
Yes! Absolutely, like all new web features make sure it meets your project standards for usability.
As you mentioned as well this:
...should produce the same results.