本文介绍了更好的方式设置flexbox项目之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要设置flexbox项目之间的最小距离,我使用 margin:0 5px .item code> margin:0 -5px 。对我来说,它似乎是一个黑客,但我找不到任何更好的方法来做到这一点。

To set the minimal distance between flexbox items I'm using margin: 0 5px on .item and margin: 0 -5px on container. For me it seems like a hack, but I can't find any better way to do this.

#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>

推荐答案


  • Flexbox没有折叠边距

  • Flexbox对表格没有任何 border-spacing

    • Flexbox doesn't have collapsing margins.
    • Flexbox doesn't have anything such as border-spacing for tables.
    • 因此,实现你要求的是有点困难。

      Therefore achieving what you are asking for is a bit more difficult.

      根据我的经验,最干净的方式不使用:first-child / :last-child
      ,并且在 flex -wrap:wrap 是在容器和 margin:5px 上设置 padding:5px 对孩子。这将在每个孩子之间以及每个孩子和他们的父母之间产生 10px 的差距。

      In my experience, the "cleanest" way that doesn't use :first-child/:last-childand 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 children and between each children and their parent.

      .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>

      这篇关于更好的方式设置flexbox项目之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:40