How do I set distance between flexbox items in CSS?

To set the distance between flexbox items in CSS, you can use the following methods:

1. Use the gap Property (Modern Browsers)

The simplest and most intuitive way to add spacing between flex items.

.container {
  display: flex;
  gap: 20px; /* Adds 20px between all flex items */
}
  • Works for both rows and columns (use row-gap or column-gap individually if needed).
  • No extra margins: Avoids unintended spacing at the edges of the container.
  • Browser Support: Supported in all modern browsers (Chrome 84+, Firefox 63+, Safari 14.1+). Not supported in IE11.

2. Use Margins on Flex Items

Add margins directly to the flex items (e.g., margin-right or margin-left):

.container {
  display: flex;
}

.item {
  margin-right: 20px; /* Adds space between items */
}

/* Remove margin from the last item */
.item:last-child {
  margin-right: 0;
}
  • Flexibility: Use margin, padding, or a combination.
  • Responsive Control: Adjust margins for different screen sizes.

3. Use justify-content to Distribute Space

Control spacing by distributing space between/around items (doesn’t set fixed gaps):

.container {
  display: flex;
  justify-content: space-between; /* Distributes space between items */
}
  • Options:
  • space-between: Equal space between items (no edge spacing).
  • space-around: Equal space around items (half-space at edges).
  • space-evenly: Equal space around and between items.

Example Comparison

MethodCode ExampleProsCons
gapgap: 20pxClean, no edge spacingNo IE11 support
Margins.item:not(:last-child) { margin-right: 20px }Full control, backward-compatibleRequires manual edge-case handling
justify-contentjustify-content: space-betweenDistributes available spaceDoesn’t set fixed gaps

Recommended Workflow

  1. For modern browsers: Use gap for simplicity.
  2. For legacy support: Use margins with :not(:last-child).
  3. For dynamic spacing: Combine justify-content with margins or gap.

Code Demo

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

<style>
.container {
  display: flex;
  gap: 20px; /* Modern method */
}

/* OR */
.item:not(:last-child) {
  margin-right: 20px; /* Legacy method */
}
</style>

Choose the method that best fits your browser requirements and design goals!

Leave a Reply

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