cssflexboxspacing

How do I set distance between flexbox items?


To set the minimal distance between flexbox items I'm using margin: 0 5px on .item and margin: 0 -5px on container. This seems like a hack. Is there another property or method intended to accomplish this goal?

#box {
  display: flex;
  width: 100px;
  margin: 0 -5px;
}

.item {
  background: gray;
  width: 50px;
  height: 50px;
  margin: 0 5px;
}
<div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>


Solution

  • Before ~20202, Flexbox didn't have anything akin to border-spacing for tables. The answer below is from that time. Now, the gap property fulfills this role and is recommended for this application.


    Flexbox doesn't have collapsing margins1. Therefore, achieving what you are asking for is a bit more difficult.

    In my experience, the "cleanest" way that doesn't use :first-child/:last-child and works without any modification on flex-wrap:wrap is to set padding:5px on the container and margin:5px on the children. That will produce a 10px gap between each child and between each child and their parent.

    JSFiddle Demo

    .upper {
      margin: 30px;
      display: flex;
      flex-direction: row;
      width: 300px;
      height: 80px;
      border: 1px red solid;
    
      padding: 5px; /* this */
    }
    
    .upper > div {
      flex: 1 1 auto;
      border: 1px red solid;
      text-align: center;
    
      margin: 5px;  /* and that, will result in a 10px gap */
    }
    
    .upper.mc /* multicol test */ {
      flex-direction: column;
      flex-wrap: wrap;
      width: 200px;
      height: 200px;
    }
    <div class="upper">
      <div>aaa<br/>aaa</div>
      <div>aaa</div>
      <div>aaa<br/>aaa</div>
      <div>aaa<br/>aaa<br/>aaa</div>
      <div>aaa</div>
      <div>aaa</div>
    </div>
    
    <div class="upper mc">
      <div>aaa<br/>aaa</div>
      <div>aaa</div>
      <div>aaa<br/>aaa</div>
      <div>aaa<br/>aaa<br/>aaa</div>
      <div>aaa</div>
      <div>aaa</div>
    </div>