使用flexbox实现此布局的最佳方法是什么?

时间:2018-01-04 00:13:20

标签: css css3 flexbox grid

我有4列和3行。最后一个图块是两行高。enter image description here

我正在研究一个如下代码:

.gridContainer {
 display: flex;
 flex-wrap: wrap;
}

.gridItems {
 width: 290px;
 height: 350px;
 margin: 0 5px 10px;
 border-radius: 4px;
}

.gridItemsTall {
  width: 290px;
  height: 710px;
  margin: 0 5px 10px;
  border-radius: 4px;
}

2 个答案:

答案 0 :(得分:1)

通过使用flex-direction: columnflex-wrap: wrapmax-height的组合,使用flexbox实现此目标的好方法。

他是你的CSS的更新:

.gridContainer {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
 max-height: 1080px; // box height *3 + margin-bottom*3 -> 350*3 + 10*3 
}

.gridItems {
  width: 290px;
  height: 350px;
  margin: 0 5px 10px;
  border-radius: 4px;
  background-color: #ccc;
}

.gridItemsTall {
  height: 710px;
}

在以下链接中,您可以找到一个实例:https://jsfiddle.net/julienvanderkluft/dkdfy7gb/

请注意,JavaScript可以操纵.gridContainer的高度以获得更大的灵活性。

答案 1 :(得分:0)

在这种情况下,您可以使用CSS网格布局而不是flexbox。您只需要在要获取两行的元素上设置grid-row: span 2



.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 50px;
  grid-gap: 10px;
  width: 200px;
}

.box {
  background: #aaa;
}

.large {
  grid-row: span 2;
}

<div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box large"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
&#13;
&#13;
&#13;