使用flexbox实现一个特定的网格



我正在使用flexxbox为我的网站创建一个网格。网格用于文章归档,每行显示3篇文章,每篇文章之间有空白。

问题是:我需要文章框从行开头开始,正好在行末尾结束。所以最明显的就是用justify-content: space-between;,我也这么做了。所以这个,除了flex-wrap: wrap创建了我需要的网格。直到我有奇数篇文章。然后,justify-content属性在行中间留下空白,如下例所示:

http://codepen.io/Naxon/pen/NbNXVj

无论容器的宽度是多少,条目都将从开始到结束,这对我来说是非常重要的。

我怎样才能做到这一点?

Flexbox不支持项目间填充,但我们可以用calc()margin来填充。Codepen

.container {
  width: 800px;
  height: 800px;
  background-color: blue;
  display: flex;
  flex-wrap: wrap;
  /*justify-content: space-between;*/
}
.item {
  width: 150px;
  height: 150px;
  background-color: green;
  /* margins */
  margin-left: 10px;
  /* figure out width taking margins into account */
  flex-basis: calc((100% - 20px) / 3);
}
/* clear margin on every third item starting with the first */
.item:nth-child(3n+1) {
  margin-left: 0;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

最新更新