Equal height rows in a flex container

前端 未结 9 710
梦如初夏
梦如初夏 2020-11-22 09:28

As you can see, the list-items in the first row have same height. But items in the second row have different height

9条回答
  •  滥情空心
    2020-11-22 10:08

    You can accomplish that now with display: grid:

    .list {
      display: grid;
      overflow: hidden;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-rows: 1fr;
      grid-column-gap: 5px;
      grid-row-gap: 5px;
      max-width: 500px;
    }
    .list-item {
      background-color: #ccc;
      display: flex;
      padding: 0.5em;
      margin-bottom: 20px;
    }
    .list-content {
      width: 100%;
    }
    • box 1

      Lorem ipsum dolor sit amet, consectetur adipisicing elit.

    • box 2

      Lorem ipsum dolor sit amet, consectetur adipisicing elit.

    • box 2

      Lorem ipsum dolor

    • box 2

      Lorem ipsum dolor

    • h1

    Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.

    The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns:

    grid-template-columns: repeat(1, 1fr); // 1 column
    grid-template-columns: repeat(2, 1fr); // 2 columns
    grid-template-columns: repeat(3, 1fr); // 3 columns
    

    and so on...

    You can mix it with media queries and change according to the size of the page.

    Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).

    More information about the grid layout:

    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

    Support of the Grid Layout accross browsers:

    https://caniuse.com/#feat=css-grid

提交回复
热议问题