Flex-box: Align last row to grid

后端 未结 29 2911
不知归路
不知归路 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:08

    As other posters have mentioned - there's no clean way to left-align the last row with flexbox (at least as per the current spec)

    However, for what it's worth: With the CSS Grid Layout Module this is surprisingly easy to produce:

    Basically the relevant code boils down to this:

    ul {
      display: grid; /* 1 */
      grid-template-columns: repeat(auto-fill, 100px); /* 2 */
      grid-gap: 1rem; /* 3 */
      justify-content: space-between; /* 4 */
    }
    

    1) Make the container element a grid container

    2) Set the grid with auto columns of width 100px. (Note the use of auto-fill (as apposed to auto-fit - which (for a 1-row layout) collapses empty tracks to 0 - causing the items to expand to take up the remaining space. This would result in a justified 'space-between' layout when grid has only one row which in our case is not what we want. (check out this demo to see the difference between them)).

    3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

    4) Similar to flexbox.

    ul {
      display: grid;
      grid-template-columns: repeat(auto-fill, 100px);
      grid-gap: 1rem;
      justify-content: space-between;
      
      /* boring properties */
      list-style: none;
      background: wheat;
      padding: 2rem;
      width: 80vw;
      margin: 0 auto;
    }
    
    li {
      height: 50px;
      border: 1px solid green;
    }

    Codepen Demo (Resize to see the effect)

提交回复
热议问题