假设我有这个:
.flex-container {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}
.flex-container > div {
background-color: DodgerBlue;
color: white;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
<div class="flex-container">
<div><a href="#">1</a></div>
<div><a href="#">2</a></div>
<div><a href="#">3</a></div>
</div>
如何使用 flexbox 对元素进行排序,以便布局像这样?
我无法更改 HTML 中 div 的顺序,因为它会危及不同 View 的布局。
最佳答案
如果你可以切换到 CSS Grid layout
就很容易了:
在
flex-cotainer
元素上创建一个网格容器将第二个元素放在第一列(使用
grid-column: 1
)跨越 2 行(使用grid-row: 1/3
).
请看下面的演示:
.flex-container {
display: inline-grid;
grid-template-columns: auto auto;
}
.flex-container div:nth-child(2) {
grid-column: 1;
grid-row: 1 / 3;
}
.flex-container > div {
background-color: DodgerBlue;
color: white;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
<div class="flex-container">
<div><a href="#">1</a></div>
<div><a href="#">2</a></div>
<div><a href="#">3</a></div>
</div>
Flexbox 解决方案是 hacky 充其量使用负边距 和已知 高度 - 见下文:
.flex-container {
display: flex;
flex-wrap: wrap;
width: 200px;
}
.flex-container div:nth-child(1) {
align-self: flex-start;
}
.flex-container div:nth-child(2) {
order: -1;
line-height: 170px;
}
.flex-container div:nth-child(3) {
margin-left: auto;
margin-top: -85px;
}
.flex-container > div {
background-color: DodgerBlue;
color: white;
width: calc(100px - 20px);
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
<div class="flex-container">
<div><a href="#">1</a></div>
<div><a href="#">2</a></div>
<div><a href="#">3</a></div>
</div>
关于html - 订购 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604932/