Flexbox: 4 items per row

前端 未结 9 1068
南笙
南笙 2020-11-22 13:01

I\'m using a flex box to display 8 items that will dynamically resize with my page. How do I force it to split the items into two rows? (4 per row)?

Here is a releva

相关标签:
9条回答
  • 2020-11-22 13:31

    Add a width to the .child elements. I personally would use percentages on the margin-left if you want to have it always 4 per row.

    DEMO

    .child {
        display: inline-block;
        background: blue;
        margin: 10px 0 0 2%;
        flex-grow: 1;
        height: 100px;
        width: calc(100% * (1/4) - 10px - 1px);
    }
    
    0 讨论(0)
  • 2020-11-22 13:33

    Flex wrap + negative margin

    Why flex vs. display: inline-block?

    • Flex gives more flexibility with elements sizing
    • Built-in white spacing collapsing (see 3 inline-block divs with exactly 33% width not fitting in parent)

    Why negative margin?

    Either you use SCSS or CSS-in-JS for the edge cases (i.e. first element in column), or you set a default margin and get rid of the outer margin later.

    Implementation

    https://codepen.io/zurfyx/pen/BaBWpja

    <div class="outerContainer">
        <div class="container">
            <div class="elementContainer">
                <div class="element">
                </div>
            </div>
            ...
        </div>
    </div>
    
    :root {
      --columns: 2;
      --betweenColumns: 20px; /* This value is doubled when no margin collapsing */
    }
    
    .outerContainer {
        overflow: hidden; /* Hide the negative margin */
    }
    
    .container {
        background-color: grey;
        display: flex;
        flex-wrap: wrap;
        margin: calc(-1 * var(--betweenColumns));
    }
    
    .elementContainer {
        display: flex; /* To prevent margin collapsing */
        width: calc(1/var(--columns) * 100% - 2 * var(--betweenColumns));
        margin: var(--betweenColumns);
    }
    
    .element {
        display: flex;
        border: 1px solid red;
        background-color: yellow;
        width: 100%;
        height: 42px;
    }
    
    0 讨论(0)
  • 2020-11-22 13:34

    I would do it like this using negative margins and calc for the gutters:

    .parent {
      display: flex;
      flex-wrap: wrap;
      margin-top: -10px;
      margin-left: -10px;
    }
    
    .child {
      width: calc(25% - 10px);
      margin-left: 10px;
      margin-top: 10px;
    }
    

    Demo: https://jsfiddle.net/9j2rvom4/


    Alternative CSS Grid Method:

    .parent {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-column-gap: 10px;
      grid-row-gap: 10px;
    }
    

    Demo: https://jsfiddle.net/jc2utfs3/

    0 讨论(0)
提交回复
热议问题