【问题标题】:Stacking flex items on top of each other将弹性项目堆叠在一起
【发布时间】:2017-10-01 05:38:22
【问题描述】:

我正在尝试使用 flexbox 构建这样的布局:

我怎样才能将这些物品堆叠在一起?

我使用 CSS 网格构建了上面屏幕截图中的内容,但没有使用 flexbox。

.grid {
  display: grid;
  height: 100%;
  grid-template-columns: 2rem repeat(2, auto) 2rem;
  grid-template-rows: 4rem 4rem auto;
  background-color: #fff;
}

.layer1 {
  background-color: rgb(64, 213, 187);
  grid-column-start: 1;
  grid-column-end: span 3;
  grid-row-start: 1;
  grid-row-end: span 3;
}

【问题讨论】:

标签: css flexbox css-grid


【解决方案1】:

注意:这个问题询问关于沿 z 轴 堆叠 flex 项目的问题。如果您来这里是为了沿 y 轴 寻找“在彼此之上堆叠 flex 项目”,请参阅此帖子:prevent flex items from rendering side to side。


Flexbox 旨在沿列或行对齐元素。它不是为堆叠而设计的。

然而,CSS Grid 非常适合这类事情。

Grid 的 CSS 替代方案是绝对定位:

(请注意,当flex item is absolutely positioned 时,它不再接受大多数弹性属性。)

article {
  display: flex;
  height: 100vh;
  position: relative;
}

section:nth-child(1) {
  flex: 1;
  background-color: turquoise;
}

section:nth-child(2) {
  position: absolute;
  top: 50px;
  left: 50px;
  right: 0;
  bottom: 0;
  background-color: salmon;
}

section:nth-child(3) {
  position: absolute;
  top: 100px;
  left: 250px;
  right: 0;
  bottom: 0;
  background-color: thistle;
}

body {
  margin: 0;
}
<article>
  <section></section>
  <section></section>
  <section></section>
</article>

jsFiddle

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多