Prefer Gaps To Margins

The article advocates for using CSS Flexbox/Grid gaps instead of margins when spacing elements in layouts, arguing that gaps provide a superior parent-to-children layout strategy compared to margin's child-to-sibling approach.

The Core Question

The fundamental decision comes down to: "whose responsibility is it for spacing, the parent or the child?" Shevlin firmly believes parents should control the layout of their children.

Problems with Margins

  • Manual Class Management: When using margins, you must manually add classes to each child element while being careful not to apply margins to the last item. This creates brittle code that requires manual updates when adding, removing, or reordering elements.
  • Complex Conditional Logic: Programmatically rendered lists require unnecessary conditional code to avoid adding margins to the final element, such as class={idx !== items.length - 1 ? "mb-4" : ""}.
  • Responsive Design Complications: Changing layouts at different breakpoints becomes cumbersome, requiring you to manually swap margin classes instead of simply changing the parent container's direction.
  • Margin Collapse Issues: Vertical margin collapse can create unpredictable spacing behavior, often requiring compensatory CSS to override default margins.

Benefits of Gaps

  • Automatic spacing: No matter how many items you have, gaps are applied correctly without conditional logic
  • Less code: Applied once to the parent container rather than individually to each child
  • Responsive-friendly: Easy to change layout direction without touching child elements
  • Wrapping support: Works seamlessly with wrapped items without needing additional margin adjustments

Bottom Line

Gaps eliminate the complexity and maintenance burden of margin-based spacing while providing cleaner, more maintainable code. The article concludes that gaps are "superior to margins in pretty much every way" for component layout systems.

Visit

Do you like my content?

Sponsor Me On Github