Search code examples
htmlcssflexboxmedia-queries

How to reorder the flex items when resizing the screen?


By using the media query and flexbox, I can only rearrange the order of the content in the second row. I want to switch order from the first row to the second row but I cannot find the solution.

I tried to change the different order number and it has no effect at all.

.item {
  width: 99%;
  height: 200px;
  background-color: blueviolet;
  display: flex;
}

.item1 {
  background-color: blue;
  width: 33%;
  height: 200px;
}

.item2 {
  background-color: cyan;
  width: 33%;
  height: 200px;
}

.item3 {
  background-color: red;
  width: 33%;
  height: 200px;
}

@media screen and (max-width: 500px) {
  div#item {
    order: 0
  }
  div#item1 {
    order: 3
  }
  div#item2 {
    order: 4
  }
  div#item3 {
    order: 1
  }
}
<div class="item" id="item"></div>
<div style="display: flex">
  <div class="item1" id="item1"></div>
  <div class="item2" id="item2"></div>
  <div class="item3" id="item3"></div>
</div>

When resizing the screen, I want to change the order between the two rows. For example, when resizing the screen, the purple and blue change position each other. How to do it?

result


Solution

  • The first row and second row are different flexboxes - you can wrap item into the container of the second row and using a wrapping flexbox using flex-wrap: wrap. After the first row is filled and if space is not left in the row, the flex items drop to the next row.

    Try changing order for the first row below:

    .wrapper {
      display: flex; /* flexbox container */
      flex-wrap: wrap; /* wrap the flexbox */
    }
    
    .item {
      width: 99%;
      height: 200px;
      background-color: blueviolet;
      display: flex;
    }
    
    .item1 {
      background-color: blue;
      width: 33%;
      height: 200px;
    }
    
    .item2 {
      background-color: cyan;
      width: 33%;
      height: 200px;
    }
    
    .item3 {
      background-color: red;
      width: 33%;
      height: 200px;
    }
    
    @media screen and (max-width: 500px) {
      div#item {
        order: 5; /* see changed order below 500px */
      }
      div#item1 {
        order: 3;
      }
      div#item2 {
        order: 4;
      }
      div#item3 {
        order: 1;
      }
    }
    <div class="wrapper">
      <div class="item" id="item"></div>
      <div class="item1" id="item1"></div>
      <div class="item2" id="item2"></div>
      <div class="item3" id="item3"></div>
    </div>