Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...