【问题标题】:How to evenly distributed margin with flex?如何使用 flex 平均分配保证金?
【发布时间】:2020-06-03 04:16:04
【问题描述】:

我想将 UI 显示为图片,并且我使用循环来创建 div ,所以我认为 flex 是最有说服力的方法。每行显示四个元素,我想将每个弹性项目的边距(左上右下)设置为相同的 10 像素。我尝试了 justify-content:space-between / space-around。这些都不是我想要的。

class App extends Component {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5];
  }

  createDiv = () => {
    // return  div className="child" />
  };

  render() {
    return (
      <div className="contianer">
        {this.arr.map((item, index) => (
          <div className="child" />
        ))}
      </div>
    );
  }
}

.contianer{
   /* width: calc(100%-20px); */
  display:flex;
  flex-flow: row wrap;
  background-color: gray;
  justify-content: space-between
  /* flex:1; */
}

.child{
  background-color: yellow;
  width: calc((100% - 50px) / 4);
  height: 100px;
  margin: 10px 5px

}

在线演示:https://stackblitz.com/edit/react-fapbff

所以有办法实现我想要的吗?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    如果您需要 flex 布局,您可以使用 align-item 和 height 作为垂直空间。

    见下面的css

     .contianer{
    
      display:flex;
      flex-flow: row wrap;
      background-color: gray;
      justify-content: space-between;
      align-items: space-between;
      height: 230px;
      padding:10px 0 0 10px
    
    }
    
    .child{
      background-color: yellow;
      width: calc((100% - 40px) / 4);
      height: 100px;
    
    } 
    
    

    但要完全控制布局,您可以使用网格布局。

    【讨论】:

      【解决方案2】:

      这是一个例子。你可以试试这段代码。它经过全面测试。希望对你有帮助。

      CSS:

      .contianer {
        display: grid;
        background-color:red;
        grid-column-gap: 10px;
        grid-template-columns: auto auto auto auto;
        grid-row-gap: 10px;
        padding: 10px;
      }
      .child {
        background-color: yellow;
        height: 100px;
      }
      


      通过使用网格,您可以实现这一点。我在您的演示“https://stackblitz.com/edit/react-fapbff”中测试了此代码。它工作正常。

      【讨论】:

        猜你喜欢
        • 2012-06-30
        • 2020-08-13
        • 1970-01-01
        • 2013-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多