Left aligned and centered grid with flexbox

后端 未结 7 2136
半阙折子戏
半阙折子戏 2020-12-30 02:21

I\'d like to implement a responsive grid-like layout using flexbox (without media queries). There can be variable number of elements in the grid. Each item should have fixed

7条回答
  •  一个人的身影
    2020-12-30 03:18

    One pretty straightforward solution is to just add a lot invisible, zero-height items at the end of your regular items:

    1
    2
    3
    4

    and

    .parent {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;
    }
    
    .parent .item,
    .parent .dummyItem{
      width: 50px;
      height: 50px;
      background: white;
      margin: 5px;
    }
    
    .parent .dummyItem {
      height: 0;
    }
    

    If your longest row can have n visible items, you'll need at least n-1 dummy items for this to work.

    The only thing that's a little bit off with this is that if there's only one row then the items won't actually be centered; instead they'll be aligned (roughly) to the left.

    Link to Codepen.

提交回复
热议问题