Left aligned and centered grid with flexbox

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 and equal width. Items should be aligned to the left. Whole group should have equal left and right margins.

It should look like that:

预期结果

This is how I tried to achieve it:

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  margin: auto;
}
.item {
  height: 200px;
  width: 200px;
  background-color: purple;
  padding: 10px;
  margin: 10px;
}
<div class="container">
  <div class="item">Flex item 1</div>
  <div class="item">Flex item 2</div>
  <div class="item">Flex item 3</div>
  <div class="item">Flex item 4</div>
  <div class="item">Flex item 5</div>
</div>

You can't achieve this with flexbox out of the box (at least I didn't manage to do it). You can try with justify-content: center; but this will center all childer and you'll get something like:

flexbox以儿童为中心

So the only solution I managed to find is to use another parent element and wrap everything in it.

Please see this CodePen http://codepen.io/justd/pen/rOeMGZ

I'm sure you'll find something working for you, just try to combine different CSS techniques.


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.


If you set an explicit width on the container, you can then apply margin: 0 auto to the containing element as it no longer spans the full width of the window.

Here is a Codepen example of what you are looking for: http://codepen.io/alexverner/pen/MaExqb

链接地址: http://www.djcxy.com/p/76048.html

上一篇: 将项目对齐到左侧,将容器对齐到中间

下一篇: 与flexbox左对齐和居中网格