Back to course

Lesson 65: Flexbox Gap Property and Alignment Pitfalls

CSS Mastery: From Zero to Hero in 100 Lessons

65. Flexbox Gap Property and Alignment Pitfalls

The gap Property (Flexbox and Grid)

The gap property (and its longhands, row-gap and column-gap) defines the spacing between flex items. This is a huge improvement over using margin, which often requires complex handling of the last/first item margins.

css .grid-like-flex { display: flex; flex-wrap: wrap;

/* Sets 20px space between items (column-gap) AND between lines (row-gap) */ gap: 20px; }

.nav-links { display: flex; column-gap: 1rem; /* Space between horizontal links */ }

Compatibility Note: The gap property in Flexbox is a newer addition and might require modern browser versions, but it is widely supported today.

Common Flexbox Pitfalls

  1. Forgetting display: flex;: If your items aren't behaving, check the container.
  2. Using justify-content on column: If flex-direction: column is set, justify-content controls vertical space, not horizontal. Conversely, align-items controls horizontal alignment.
  3. Mixing width and flex-basis: Stick primarily to flex shorthand or flex-basis to define the main size of an item when using Flexbox, or you might get confusing results.