cssflexboxdirection

How can I reverse all the elements of a flexbox in CSS?


I'm trying to sort elements of a flexbox from the last to the first.

I tried using flex-direction: row-reverse; but it only reverses the lines, not the whole container.

The result:

the result

It sorts like 3-2-1-(...)-9-8-7, what I want is 9-8-7-(...)-3-2-1*

How can I reverse all elements?

.container {
  display: flex;
  flex-wrap: wrap;
  height: 10rem;
  flex-direction: row-reverse;
}

.container .item {
  height: 30%;
  width: 30%
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
</div>


Solution

  • Just use flex-wrap: wrap-reverse See the docs: https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap

    .container {
      display: flex;
      flex-wrap: wrap-reverse;
      height: 10rem;
      flex-direction: row-reverse;
    }
    
    .container .item {
      height: 30%;
      width: 30%
    }
    <div class="container">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
      <div class="item">6</div>
    </div>