html - flex 盒订单 : I want box to open under a element which is not a sibling

标签 html css flexbox

当屏幕尺寸较小时,我希望黄色在蓝色下方。

我知道为什么它现在不起作用了,因为黄色不是其他盒子的兄弟,我该怎么做才能解决这个问题?

https://jsfiddle.net/0vbdcms0/

.container1 {
  display: flex;
  flex-flow: column;
}

.container2 {
  display: flex;
  flex-flow: row;
}

.box {
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 5px 5px 5px 5px;
}

#b1 {
  background-color: red;
}

#b2 {
  background-color: blue;
}

#b3 {
  background-color: green;
}

#b4 {
  background-color: yellow;
}

@media screen and (max-width:500px) {
.container2 {
  display: flex;
  flex-flow: column;
}
  #b1 {
    order: 1;
    -webkit-order: 1;
  }

  #b2 {
    order: 2;
    -webkit-order: 2;
  }

  #b3 {
    order: 4;
    -webkit-order: 4;
  }

  #b4 {
    order: 3;
    -webkit-order: 3
  }
}
<div class="container1">
  <div class="container2">
    <div class="box" id="b1"></div>
    <div class="box" id="b2"></div>
    <div class="box" id="b3"></div>
  </div>
  <div class="box" id="b4"></div>
</div>

我需要添加更多文本以满足 SO,我想我在上面的文本中获得了所有相关信息:)

最佳答案

使用 order 将不起作用,因为顺序与 container 而不是 DOM 有关。

The CSS order property specifies the order used to lay out flex items in their flex container. Elements are laid out in the ascending order of the order value. Elements with the same order value are laid out in the order in which they appear in the source code.

MDN - "order"

CSS Grid 可以做到这一点。

Codepen Demo

.container {
  padding: 5px;
  display: grid;
  width: 500px;
  margin: 1em auto;
  grid-auto-columns: 50px;
  grid-auto-rows: 50px;
  grid-gap: 5px;
}

.box {
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

#b1 {
  background-color: red;
  grid-column-start: 1;
  grid-column-end: 2;
}

#b2 {
  background-color: blue;
  grid-column-start: 2;
  grid-column-end: 3;
}

#b3 {
  background-color: green;
  grid-column-start: 3;
  grid-column-end: 4;
}

#b4 {
  background-color: yellow;
  grid-column-start: 1;
  grid-column-end: 2;
}

@media screen and (max-width: 500px) {
  #b1,
  #b2,
  #b3,
  #b4 {
    grid-column-start: 1;
    grid-column-end: 2;
  }
  #b3 {
    grid-row-start: 4;
    grid-row-end: 5;
  }
  #b4 {
    grid-row-start: 3;
    grid-row-end: 4;
  }
}
<div class="container">
  <div class="box" id="b1"></div>
  <div class="box" id="b2"></div>
  <div class="box" id="b3"></div>
  <div class="box" id="b4"></div>
</div>

It might be possible in Flexbox但并非所有浏览器都完全支持必要的属性。我认为在撰写本文时它只是 Firefox。

关于html - flex 盒订单 : I want box to open under a element which is not a sibling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755418/

相关文章:

python - 在 BeautifulSoup 中索引多个表

php - MySql - 三个成功连接的表,但未能获得一列结果?

html - 图像防止 flex 元素拉伸(stretch)到屏幕底部

html - 如何使用 flexbox 将 2 行居中?

html - 我的 Flex 在行中显示六个 div,而不是三个?

javascript - 您如何缩小内部和数组的 promise 功能?

javascript - 更新条形图时删除旧文本标签

css - 在 Bootstrap Navbar 中居中一个元素

javascript - 将事件悬停在更高 z-index 覆盖的元素上?

javascript - 将样式添加到随机加载的 div - 无法正常工作