Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

css - Stacking flex items on top of each other

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

enter image description here

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 is designed to align elements along columns or rows. It is not designed for stacking.

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...