Reorder columns in reverse order

12.7k views Asked by At

I have a list of flex items within a flexbox. The order of the items matter, and for accessibility purposes, the items need to show up in the correct order in the dom.

[[itema][itemb][itemc]]

When the flexbox shrinks I would like to have the items wrap in reverse order, e.g. itema wraps first, etc. Is there any way to have the itema wrap first? Thanks!

Edit:

Here is the code

<div class="flex">
    <div class="container">
        <div class="item">item1</div>
        <div class="item orange">item2</div>
        <div class="item blue">item3</div>
    </div>
    <div class="last-item green">menu</div>
</div>

.flex {
    display: flex;
    background-color: yellow;
    height: 80px;
    overflow: hidden;
    color: #fff;
}

.container {
    display: flex;
    flex: 1 1 auto;
    flex-wrap: wrap;
}

.item {
    flex: 0 0 auto;
    background-color: red;
    height: 80px;
    padding: 0 40px;
}

.last-item {
    width: 40px;
    flex: 0 0 auto;
    height: 80px;
}

JSFiddle

All the behavior is as desired except I want the first item to wrap first. Any ideas? Thanks!

2

There are 2 answers

3
m4n0 On

You can use the flex-direction: column-reverse to get your solution.

@media (max-width: 768px) {
  .flex-box {
    display: flex;
    flex-direction: column-reverse;
  }
}
.first,
.second,
.third {
  display: inline-block;
}
<div class="flex-box">
  <div class="first">
    <p>First Box</p>
    <img src="http://placehold.it/300x300" />
  </div>
  <div class="second">
    <p>Second Box</p>
    <img src="http://placehold.it/300x300" />
  </div>
  <div class="third">
    <p>Third Box</p>
    <img src="http://placehold.it/300x300" />
  </div>
</div>

JSfiddle Demo

0
J.W. On

To make item1 wrap first, you can use flex-wrap: wrap-reverse on your flex container.

Try this simplified version of you code:

<div class="container">
    <div class="item">item1</div>
    <div class="item orange">item2</div>
    <div class="item blue">item3</div>
</div>

.container {
    display: flex;
    flex: 0 1 auto;
    flex-wrap: wrap-reverse;
}

.item {
    background-color: red;
    height: 80px;
    padding: 0 40px;
}

.orange {
  background-color: orange;
}
.blue {
    background-color: blue
}

See the MDN reference for browser support.