首页 > 解决方案 > Flex wrap 反向断裂?

问题描述

.flex {
  display: flex;
  flex-wrap: wrap;
}

.flex>div {
  flex: 1;
  min-width: 100px;
}

.a {
  background-color: green;
}

.b {
  background-color: yellow;
}

.c {
  background-color: red;
}

.d {
  background-color: purple;
}
<div class="flex">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
</div>

当窗口很宽时,上面的代码如下所示:

在此处输入图像描述

当它很小时,它看起来像这样:

在此处输入图像描述

这是我想要的包装行为,但不是 D(紫色)是全角的,我希望 A(绿色)是全角的,B、C、D 应该在第二行。

flex-wrap: wrap-reverse; flex-direction: row-reverse几乎可以工作,但它也会颠倒项目的顺序,这是我不想要的。

有什么办法可以使这项工作?

标签: cssflexbox

解决方案


您可以考虑如下的 order 属性:

.flex {
  display: flex;
  flex-wrap: wrap-reverse;
  flex-direction: row-reverse;
}

.flex>div {
  flex: 1;
  min-width: 100px;
}

.a {
  background-color: green;
  order:3;
}

.b {
  background-color: yellow;
  order:2;
}

.c {
  background-color: red;
  order:1;
}

.d {
  background-color: purple;
}
<div class="flex">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
</div>

如果是动态内容(元素数量未知,您可以考虑nth-last-child如下。您可以使用 SASS/LESS 轻松生成的代码

.flex {
  display: flex;
  flex-wrap: wrap-reverse;
  flex-direction: row-reverse;
}

.flex>div {
  flex: 1;
  min-width: 100px;
  color:#fff;
}
.flex>div:nth-last-child(1) {order:1}
.flex>div:nth-last-child(2) {order:2}
.flex>div:nth-last-child(3) {order:3}
.flex>div:nth-last-child(4) {order:4}
.flex>div:nth-last-child(5) {order:5}
.flex>div:nth-last-child(6) {order:6}
.flex>div:nth-last-child(7) {order:7}
.flex>div:nth-last-child(8) {order:8}
.flex>div:nth-last-child(9) {order:9}
.flex>div:nth-last-child(10) {order:10}
/*.flex>div:nth-last-child(N) {order:N} */

.flex>div:nth-child(odd){
  background-color: green;
}
.flex>div:nth-child(even){
  background-color: purple;
}
<div class="flex">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
  <div>G</div>
  <div>H</div>
  <div>I</div>
  <div>J</div>
</div>


推荐阅读