'How to reorder CSS Flexbox
I have a flex container with flex-direction: row and n items, they do not have fixed height or width. On desktop I am showing 2 columns with an exact order. On mobile it is one column but the order is not what I want. Basically I want to show the items from the second column after the items from the first column . How to reorder them to achieve the desired result? Here is an example.
On Desktop two columns
item1 item2
item3 item4
item5 item6
Desired result with one column
item1
item3
item5
item2
item4
item6
Here is a html and css
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1 0 50%;
}
@media only screen and (max-width: 520px) {
.item {
flex: 100%;
}
}
<div class="container">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
</div>
Solution 1:[1]
Just add this
.item:nth-child(2n - 1) {
order: -1;
}
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1 0 50%;
}
@media only screen and (max-width: 520px) {
.item {
flex: 100%;
}
.item:nth-child(2n - 1) {
order: -1;
}
}
<div class="container">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
</div>
Solution 2:[2]
You can use flex and order for that:
.container {
display: flex;
flex-wrap: wrap;
width: 100%;
}
.item {
width: 50%;
padding-bottom: 20px;
}
@media screen and (max-width: 800px) {
.container {
flex-direction: column;
}
.item {
width: 100%;
}
.item3 {
order: 2;
}
.item5 {
order: 3;
}
.item2 {
order: 4;
}
.item4 {
order: 5;
}
.item6 {
order: 6;
}
}
<div class="container">
<div class="item item1">item1</div>
<div class="item item2">item2</div>
<div class="item item3">item3</div>
<div class="item item4">item4</div>
<div class="item item5">item5</div>
<div class="item item6">item6</div>
</div>
Solution 3:[3]
You can use the order property with flexbox. Here is the resource => https://developer.mozilla.org/en-US/docs/Web/CSS/order
@media (max-width: 520px) {
.item:nth-child(1) {
order: 1;
}
.item:nth-child(2) {
order: 4;
}
.item:nth-child(3) {
order: 2;
}
.item:nth-child(4) {
order: 5;
}
.item:nth-child(5) {
order: 3;
}
.item:nth-child(6) {
order: 6;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | doÄŸukan |
| Solution 2 | |
| Solution 3 |
