Flex-box: Align last row to grid

后端 未结 29 2473
不知归路
不知归路 2020-11-22 02:54

I have a simple flex-box layout with a container like:

.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

29条回答
  •  清酒与你
    2020-11-22 03:16

    Assuming:

    • You want 4 column grid layout with wrapping
    • The number of items is not necessarily a multiple of 4

    Set a left margin on every item except 1st, 5th and 9th item and so on. If the left margin is 10px then each row will have 30px margin distributed among 4 items. The percentage width for item is calculated as follows:

    100% / 4 - horizontal-border - horizontal-padding - left-margin * (4 - 1) / 4
    

    This is a decent workaround for issues involving last row of flexbox.

    .flex {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      margin: 1em 0 3em;
      background-color: peachpuff;
    }
    
    .item {
      margin-left: 10px;
      border: 1px solid;
      padding: 10px;
      width: calc(100% / 4 - 2px - 20px - 10px * (4 - 1) / 4);
      background-color: papayawhip;
    }
    
    .item:nth-child(4n + 1) {
      margin-left: 0;
    }
    
    .item:nth-child(n + 5) {
      margin-top: 10px;
    }
    1
    2
    3
    4
    1
    2
    3
    4
    5
    6
    1
    2
    3
    4
    5
    6
    7
    8
    9

提交回复
热议问题