Reverse Element Order with CSS Flexbox

By  on  

CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics and accessibility aside, I was recently hoping to find out if you could render elements in reverse order using only CSS, since in previous years we'd need to shift the DOM around

Let's assume we have the following HTML:

<ul">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
</ul>

Depending upon whether you'd like the elements to display vertically or horizontally, you'll change the value of flex-direction to reverse the order of elements:

/* show reverse by horizontal row */
.row-reverse { display: flex; flex-direction: row-reverse; }

/* show reverse by vertical column */
.column-reverse { display: flex; flex-direction: column-reverse; }

row-reverse displays the elements in reverse order horizontally, while column-reverse displays the elements in reverse order vertically.

I recently used this technique to overcome a frustrating problem with AngularJS, whereby I was iterating over an object's keys; there was no way to iterate over these keys in reverse order from the template, so I reversed the elements with CSS.  Not ideal but it did the job in the short term.

I remember when Flexbox was meant to change CSS in amazing ways, and while I don't think Flexbox's usage has changed the web world, I do think that we do have awesome tricks like this.  I hope to expand my Flexbox horizons but until then I'll continue sharing snippets like this!

Recent Features

Incredible Demos

  • By
    Flexbox Equal Height Columns

    Flexbox was supposed to be the pot of gold at the long, long rainbow of insufficient CSS layout techniques.  And the only disappointment I've experienced with flexbox is that browser vendors took so long to implement it.  I can't also claim to have pushed flexbox's limits, but...

  • By
    Element Position Swapping Using MooTools 1.2

    We all know that MooTools 1.2 can do some pretty awesome animations. What if we want to quickly make two element swap positions without a lot of fuss? Now you can by implementing a MooTools swap() method. MooTools 1.2 Implementation MooTools 1.2 Usage To call the swap...

Discussion

  1. One BIG issue with flexbox, grid and change item order is that, when you select text on page, you select it in source order.

    https://codepen.io/kartofelek007/pen/moyKwz

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!