5 items per row, auto-resize items in flexbox

后端 未结 4 1568

I have this at the moment:

4条回答
  •  有刺的猬
    2020-11-27 18:42

    You are right in giving a flex-basis: 20% but you have to adjust for the 4px margin on each flex item for it to wrap properly.


    Equal Width Flex items in the last row

    Use flex: 0 1 calc(20% - 8px) - this means the item won't grow beyond 20% of width (adjusting for margin) and can shrink based on the container width. See demo below:

    .container {
      background: gray;
      width: 600px;
      height: 200px; /* height given for illustration */
      display: flex;
      flex-flow: row wrap;
      position: relative;
    }
    
    .item {
      background: blue;
      margin: 4px;
      flex: 0 1 calc(20% - 8px); /* <-- adjusting for margin */
    }


    Another approach is a bit hacky - you can keep flex-grow set to one and flex-basis: calc(20% - 4px) using flex: 1 1 calc(20% - 4px), and use a pseudo element that fills the remaining space:

    .container {
      background: gray;
      width: 600px;
      height: 200px; /* height given for illustration */
      display: flex;
      flex-flow: row wrap;
      position: relative;
    }
    
    .item {
      background: blue;
      margin: 4px;
      flex: 1 1 calc(20% - 8px); /* <-- adjusting for margin */
    }
    
    .container:after {
      content: '';
      display: block;
      flex: 999; /* grow by a large number */
    }

    If you don't have the n item per row requirement then you can refer this:

    • Unordered list that acts like grid-auto-flow dense

    Flex items in last row expands to fill the available space

    If in a row you have less than 5 items and you want them to fill in the remaining space use flex: 1 1 calc(20% - 8px) (note that flex-grow is set to 1 here so that the flex items in the last rows expand to fill the remaining space):

    .container {
      background: gray;
      width: 600px;
      height: 200px;  /* height given for illustration */
      display: flex;
      flex-flow: row wrap;
      position: relative;
    }
    
    .item {
      background: blue;
      margin: 4px;
      flex: 1 1 calc(20% - 8px);  /* <-- adjusting for margin */
    }

提交回复
热议问题