Home > Software design >  How to reorder CSS Flexbox
How to reorder CSS Flexbox

Time:03-16

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 >
  <div >item1</div>
  <div >item2</div>
  <div >item3</div>
  <div >item4</div>
  <div >item5</div>
  <div >item6</div>
</div>

CodePudding user response:

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 >
  <div >item1</div>
  <div >item2</div>
  <div >item3</div>
  <div >item4</div>
  <div >item5</div>
  <div >item6</div>
</div>

CodePudding user response:

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 >
  <div >item1</div>
  <div >item2</div>
  <div >item3</div>
  <div >item4</div>
  <div >item5</div>
  <div >item6</div>
</div>

CodePudding user response:

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;
  }
}
  • Related