Left aligned and centered grid with flexbox

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

    I think you just need to give your grid container some kind of max-width, then your auto margins should work too. What's happening is your container is expanding 100% to either side so there's nothing for the auto margin to work with.

    So if you want it to expand to 3 items per row max, just set the max-width to 660 (item width + item margin):

    .container {
      max-width: 660px;
      margin: 0 auto;
      display: flex;
      flex-flow: row-wrap;
    }
    .item {
      width: 200px;
      height: 200px;
      margin: 10px;
    }
    

    Here's a Codepen: http://codepen.io/kgrote/pen/qbpGWZ

    The container will fluidly expand until its maximum width is met, then center itself while keeping its children in a left-aligned grid. As the container shrinks, the children will stack as needed.

提交回复
热议问题