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

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

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!