【问题标题】:how can I make the child divs of a flex container have the same spacing using flexbox? [duplicate]如何使用 flexbox 使 flex 容器的子 div 具有相同的间距? [复制]
【发布时间】:2021-11-23 05:33:10
【问题描述】:

我想做这样的图片,

但我不知道如何确保每列之间有20px 的分隔每列之间。我正在做margin-right: 20px;,但最后一列会有问题。 使用flexbox 解决此问题的最佳做法是什么?

.flex_container{
  display:flex;
  border:1px solid red;
  width:100%;
}

.flex_container div{
 width:100%;
 border:1px solid blue;
 margin-right: 20px;
 background:yellow;
 height:400px;
}
<div class="flex_container">
  <div>col 1</div>
  <div>col 2</div>
  <div>col 3</div>
  <div>col 4</div>
</div>

【问题讨论】:

  • 尝试使用gap属性
  • @Sfili_81 这行得通,你能回答一下吗?

标签: css


【解决方案1】:

您也可以使用justify-content 属性来获得相等的空间,如下面的 sn-p :

See more about justify-content here

但是当你使用它时,你会看到它在 width 必须是绝对值时起作用

.flex_container {
  display: flex;
  border: 1px solid red;
  width: 100%;
  flex-flow:row;
  justify-content:space-between;
}

.flex_container div {
  width: 100px;
  border: 1px solid blue;
  background: yellow;
  height: 400px;
}
<div class="flex_container">
  <div>col 1</div>
  <div>col 2</div>
  <div>col 3</div>
  <div>col 4</div>
</div>

【讨论】:

  • 这不是操作想要的
  • 是的,改成space-between OP是什么意思,你能告诉@Sfili_81
  • @Rana, OP 表示original poster :)
【解决方案2】:

大多数人已经指出要在容器上设置“间隙”。而且,从 flex 项中移除宽度和边距,并设置 flex-grow。

.flex_container{
  display:flex;
  border:1px solid red;
  width:100%;
  gap: 20px;
}

.flex_container div{
  border:1px solid blue;
  background:yellow;
  height:400px;
  flex-grow: 1;
}

【讨论】:

    【解决方案3】:

    只需将gap:20px; 添加到您的弹性容器中

    .flex_container{
      display:flex;
      border:1px solid red;
      width:100%;
      gap: 20px;
      
    }
    
    .flex_container div{
     width:100%;
     border:1px solid blue;
     /*margin-right: 20px; not necessary*/
     background:yellow;
     height:400px;
    }
    <div class="flex_container">
      <div>col 1</div>
      <div>col 2</div>
      <div>col 3</div>
      <div>col 4</div>
    </div>

    【讨论】:

    • 我不知道这个属性,谢谢! :)
    • 你的回答也对
    【解决方案4】:

    此解决方法针对除最后一个以外的所有孩子 :)

    .flex_container{
      display:flex;
      border:1px solid red;
      width:100%;
    }
    
    .flex_container div{
     width:100%;
     border:1px solid blue;
     background:yellow;
     height:400px;
    }
    
    .flex_container div:not(:last-child) {
      margin-right: 20px;
    }
    <div class="flex_container">
      <div>col 1</div>
      <div>col 2</div>
      <div>col 3</div>
      <div>col 4</div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2017-03-15
      相关资源
      最近更新 更多