CSS

Distributing Space Evenly Between Flex Items with gap

Utilize CSS Flexbox `gap` property and `justify-content` to distribute space efficiently and consistently between items, avoiding common margin collapse issues.

<style>
  .flex-container-gap {
    display: flex;
    flex-wrap: wrap;
    gap: 20px 30px; /* row-gap column-gap */
    background-color: #f9f9f9;
    padding: 20px;
    border: 1px solid #ddd;
  }

  .flex-item-gap {
    background-color: #d1e7dd;
    border: 1px solid #84b6a9;
    padding: 15px;
    flex: 1 1 calc(33.33% - 20px); /* Example for 3 items per row with gap */
    box-sizing: border-box;
    min-width: 120px;
    text-align: center;
  }

  /* Example of justify-content for different spacing behaviors */
  .flex-container-space-between {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    padding: 20px;
    border: 1px solid #ccc;
    margin-top: 30px;
    background-color: #f0f8ff;
  }
</style>

<h2>Flexbox with `gap` property</h2>
<div class="flex-container-gap">
  <div class="flex-item-gap">Item 1</div>
  <div class="flex-item-gap">Item 2</div>
  <div class="flex-item-gap">Item 3</div>
  <div class="flex-item-gap">Item 4</div>
  <div class="flex-item-gap">Item 5</div>
  <div class="flex-item-gap">Item 6</div>
</div>

<h2>Flexbox with `justify-content: space-between` and `gap`</h2>
<div class="flex-container-space-between">
  <div class="flex-item-gap">First</div>
  <div class="flex-item-gap">Middle</div>
  <div class="flex-item-gap">Last</div>
</div>
How it works: This snippet shows how to effectively use the `gap` property with CSS Flexbox to create consistent spacing between items, both horizontally and vertically, without resorting to complex margin tricks. The `gap` property applies spacing *between* items, not on their edges, simplifying layout. It can take one value (for both row and column gap) or two values (row-gap column-gap). The `justify-content: space-between` example demonstrates how to combine `gap` with alignment properties to distribute items and the remaining space within the container.

Need help integrating this into your project?

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

Hire DigitalCodeLabs