Don’t Use Margins For Spacing Between Components, Use Gaps


Our layout can be magical and powerful with flex and grid.

Support Us




Let’s say we have multiple components and want to have 3 in each row. Also, spacing between them should be 1rem.

Components don’t care about that. Only the parent does:

.parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 1rem;

And that it! Whichever component we stick here, it will magically work (if we don’t have a large min-width set on them).

What about tablet and mobile designs? The tablet should display 2 items per row, and mobile just 1.

Well, we just need to add 2 different media queries; one with grid-template-columns: 1fr 1fr; for tablet, and grid-template-columns: 1fr; for mobile.

And our layout will work all the time with just a few simple lines!

gap is a replacement for all various combinations of parent + child selectors and margin top/right/bottom/left.


Leave a comment

Your email address will not be published. Required fields are marked *