css - 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
几乎可以工作,但它也会颠倒项目的顺序,这是我不想要的。
有什么办法可以使这项工作?
解决方案
您可以考虑如下的 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>
推荐阅读
- vue.js - 在哪里放置 Vue 配置(在 Ionic 项目中)
- javascript - React.js 错误:TypeError:无法读取未定义的属性“地图”
- next.js - NextJS v10 Image 组件在有 basePath 时无法提供图像
- pandas - 按存储在不同列中的复合群组排序
- sql - 一列的默认值可以是SQL中的另一列吗?
- qt - 在一个窗口中显示多个类 QML
- wordpress - 如何在 WP-Rest 上获取类别的 ACF?
- youtube-api - YouTube API 缩略图集端点抛出 403 被禁止
- php - 如何在 PHP 8.0 中键入 Juggle?
- php - phpmyadmin 加载 html 代码而不是普通页面