将弹性项目彼此堆叠 [英] Stacking flex items on top of each other

查看:73
本文介绍了将弹性项目彼此堆叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a layout like this one with flexbox:

如何将这些项目彼此堆叠?

how can I stack the items on top of one another?

我使用CSS网格在上述屏幕截图上构建了内容,但未能

I build what's on the above screenshot using CSS grid, but failing to do this with 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;
}


推荐答案

注意:问题询问有关沿 z轴堆叠柔性物品的问题。如果您是来这里沿着 y轴寻找将弹性项目彼此叠放的,请参阅此文章:防止从渲染一侧到另一侧的弹性项目

NOTE: This question asks about stacking flex items along the z-axis. If you came here looking for "Stacking flex items on top of each other" along the y-axis, see this post instead: prevent flex items from rendering side to side.

Flexbox的设计使元素沿列或行对齐。它不是为堆栈而设计的。

Flexbox is designed to align elements along columns or rows. It is not designed for stacking.

CSS Grid非常适合这种事情。

CSS Grid, however, is perfect for this sort of thing.

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

A CSS alternative to Grid would be absolute positioning:

(请注意,当弹性商品已完全定位,它不再接受大多数弹性属性。)

(Note that when a flex item is absolutely positioned, it no longer accepts most flex properties.)

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>

这篇关于将弹性项目彼此堆叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆