Stacking flex items on top of each other

谁都会走 提交于 2019-12-14 03:25:43

问题


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

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

回答1:


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>

jsFiddle



来源:https://stackoverflow.com/questions/43759195/stacking-flex-items-on-top-of-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!