Flexbox: 4 items per row

前端 未结 9 1169
南笙
南笙 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: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

    ...
    :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;
    }
    

提交回复
热议问题