【问题标题】:What's the best way to achieve this layout with flexbox?使用 flexbox 实现这种布局的最佳方法是什么?
【发布时间】:2018-01-04 10:47:13
【问题描述】:

我有 4 列和 3 行。最后一格高两行。

我正在编写如下代码:

.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;
}

【问题讨论】:

标签: css flexbox grid


【解决方案1】:

使用 flexbox 实现此目的的一个好方法是使用 flex-direction: columnflex-wrap: wrapmax-height 的组合。

他是你 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/

请注意,.gridContainer 的高度可以通过 JavaScript 进行操作以获得更大的灵活性。

【讨论】:

  • 谢谢!这正是我想要的。
【解决方案2】:

在这种情况下,您可以使用 CSS Grid 布局而不是 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2015-07-16
    相关资源
    最近更新 更多