使用flexbox实现某个网格

时间:2016-11-13 10:30:02

标签: html css flexbox

我使用flexbox为我的网站创建网格。网格用于文章存档,每行应显示3篇文章,每篇文章之间有边距。

问题是:我需要文章框从行的开头开始,并在行的结尾处完成。所以显而易见的是使用justify-content: space-between;,我做了。所以,除了flex-wrap: wrap之外,还创建了我需要的网格。直到我有一些奇怪的文章。然后justify-content属性在行的中间留下了一个空格,如下例所示:

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

对我来说非常重要的是,无论容器的宽度是多少,物品都会从头开始,然后结束。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

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>