Left aligned and centered grid with flexbox

后端 未结 7 2078
半阙折子戏
半阙折子戏 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:

    <div class="parent">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="dummyItem"></div>
      <div class="dummyItem"></div>
      <div class="dummyItem"></div>
      <div class="dummyItem"></div>
    </div>
    

    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.

    0 讨论(0)
提交回复
热议问题