CSS

Consistent Spacing Between Flex Items with `gap`

Simplify spacing between Flexbox items using the modern `gap` property, eliminating the need for complex margin tricks and ensuring clean, consistent layouts for lists or grids.

.flex-container {
  display: flex;
  flex-wrap: wrap; /* Allows items to wrap to the next line */
  gap: 15px; /* Applies 15px spacing between all items, horizontally and vertically */
  padding: 10px;
  border: 1px dashed #aaa;
}

.flex-item {
  width: 100px; /* Example fixed width */
  height: 70px;
  background-color: #ffe6cc;
  border: 1px solid #ffcc99;
  display: flex; /* For centering content within item */
  justify-content: center;
  align-items: center;
  font-weight: bold;
}
How it works: The `gap` property (formerly `grid-gap`) provides a clean and efficient way to add consistent spacing between flex items, both horizontally and vertically when `flex-wrap` is used. Unlike traditional margins, `gap` only applies space *between* items, avoiding issues with extra space at the edges of the container, simplifying responsive designs and item alignment.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs