【问题标题】:Flexbox margins between elements and zero margins to parent wrapper [duplicate]元素之间的弹性框边距和父包装器的零边距[重复]
【发布时间】:2019-11-22 11:14:23
【问题描述】:

代码沙盒示例:https://codesandbox.io/embed/silly-firefly-87cov

我们在父元素中有随机数量的元素。元素使用 flexbox 将自己定位到合适的位置。

问题:如何只在元素之间而不是父元素之间做边距?

【问题讨论】:

    标签: css reactjs flexbox


    【解决方案1】:

    我想与您分享一个 CSS 网格解决方案。我们可以使用grid-gap 来指定孩子之间的间距。这使我们可以删除 margin 并专注于父元素中更具声明性的布局。

    const Parent = styled.div`
      display: grid;
      grid-auto-rows: 300px;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      grid-gap: 5px;
    `;
    
    const Element = styled.div`
      background-color: black;
      border: 1px solid green;
      color: white;
    `;
    

    CodeSandbox

    【讨论】: